Random User Generation with Pydantic

  • Share this:

Code introduction


This function uses the Pydantic library to create a random user object, including name, age, and an optional email address. The age must be greater than 0.


Technology Stack : Pydantic

Code Type : Function

Code Difficulty : Intermediate


                
                    
from pydantic import BaseModel, validator
from typing import Optional
import random

class User(BaseModel):
    name: str
    age: int
    email: Optional[str] = None

    @validator('age')
    def check_age(cls, v):
        if v <= 0:
            raise ValueError('Age must be greater than 0')
        return v

def generate_random_user():
    names = ['Alice', 'Bob', 'Charlie', 'David', 'Eve']
    return User(
        name=random.choice(names),
        age=random.randint(18, 65),
        email=f"{random.choice(names)}@example.com" if random.choice([True, False]) else None
    )

# JSON representation                
              
Tags: