๐ก๏ธ Pydantic Models
Pydantic performs data validation and settings management using Python type annotations.
Mastering this concept will significantly boost your Python data science skills!
๐ป Code Example:
from pydantic import BaseModel, EmailStr, field_validator, model_validator, Field from typing import Optional, List from datetime import datetime from enum import Enum # 1. Enum for valid courses class CourseType(str, Enum): python = "Infinite Python" ai = "Infinite AI" devops = "DevOps" # 2. Nested model class Enrollment(BaseModel): course : CourseType enrolled_at: datetime = Field(default_factory=datetime.utcnow) score : float = Field(ge=0, le=100, description="Score 0โ100") # 3. Main model with validators class PynfinityUser(BaseModel): username : str = Field(min_length=3, max_length=30) email : str is_premium: bool = False score : float = Field(default=0.0, ge=0.0, le=100.0) enrollments: List[Enrollment] = [] @field_validator("username") @classmethod def username_lowercase(cls, v: str) -> str: return v.strip().lower() @field_validator("email") @classmethod def email_must_be_valid(cls, v: str) -> str: if "@" not in v or "." not in v.split("@")[-1]: raise ValueError("Invalid email format") return v.lower() @model_validator(mode="after") def premium_requires_score(self) -> "PynfinityUser": if self.is_premium and self.score < 50: raise ValueError("Premium users must have score >= 50") return self @property def display_name(self) -> str: return f"{'โญ' if self.is_premium else ''} {self.username.title()}" # 4. Usage user = PynfinityUser( username="SANTOSHTVK", email="TVK@Pynfinity.COM", is_premium=True, score=95.5, enrollments=[ Enrollment(course=CourseType.python, score=95.5), Enrollment(course=CourseType.ai, score=88.0), ], ) print("Display:", user.display_name) print("Courses :", [e.course.value for e in user.enrollments]) print("\nJSON:") print(user.model_dump_json(indent=2)) # 5. Validation error handling from pydantic import ValidationError try: PynfinityUser(username="x", email="bad-email", score=-5) except ValidationError as e: print("\nValidation errors:") for err in e.errors(): print(f" [{'.'.join(str(l) for l in err['loc'])}] {err['msg']}")
Keep exploring and happy coding! ๐ป