You can download this code by clicking the button below.
This code is now available for download.
This function uses the Pydantic library to define a user model and uses a generator function to randomly generate user data, then creates a user instance using the model.
Technology Stack : Pydantic
Code Type : Function
Code Difficulty : Intermediate
from pydantic import BaseModel, Field, 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 cannot be negative')
return v
def generate_user_data():
users = [
{"name": "Alice", "age": 30, "email": "alice@example.com"},
{"name": "Bob", "age": 25},
{"name": "Charlie", "age": 22, "email": "charlie@example.com"}
]
return random.choice(users)
def xxx():
user_data = generate_user_data()
user = User(**user_data)
return user