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 user model and generate a random user instance. The user model includes id, name, age, and hobbies fields, where age and hobbies are optional. The function uses the random library to generate random data.
Technology Stack : Pydantic, random
Code Type : Function
Code Difficulty : Intermediate
from pydantic import BaseModel, Field
from typing import Optional, List
import random
class User(BaseModel):
id: int
name: str
age: Optional[int] = Field(None, ge=0)
hobbies: Optional[List[str]] = Field(None, min_items=1)
def generate_random_user():
hobbies = ['reading', 'running', 'swimming', 'cycling', 'hiking', 'dancing', 'painting', 'cooking', 'gaming', 'traveling']
name = random.choice(['Alice', 'Bob', 'Charlie', 'David', 'Eva', 'Frank', 'Grace', 'Hannah', 'Ivy', 'Jack'])
age = random.randint(18, 70)
random_hobbies = random.sample(hobbies, random.randint(1, len(hobbies)))
return User(id=random.randint(1, 1000), name=name, age=age, hobbies=random_hobbies)
# JSON representation of the code information