You can download this code by clicking the button below.
This code is now available for download.
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