Pydantic Person Model with Random Generation

  • Share this:

Code introduction


This code defines a Pydantic model named Person, which can be used to validate and create data with specific fields. The function generate_random_person uses this model to generate a person with a random name and age.


Technology Stack : Pydantic

Code Type : Pydantic Model

Code Difficulty : Intermediate


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

class Person(BaseModel):
    name: str
    age: int = Field(default=18, ge=0, le=120)
    email: Optional[str] = None

def generate_random_person():
    person = Person(
        name=random.choice(['Alice', 'Bob', 'Charlie', 'David', 'Eva']),
        age=random.randint(18, 30)
    )
    return person                
              
Tags: