Python Data Validation

By : test

Language: python

Date Published: 2 weeks, 3 days ago

🔹 Overview

Data validation ensures your input matches the expected structure before being processed. Libraries like pydantic make it painless.


🔹 Using pydantic

Style : Dark Mode : Line Number: Download Font Size:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
from pydantic import BaseModel, EmailStr, ValidationError

# Define a schema for validation
class User(BaseModel):
    name: str
    email: EmailStr
    age: int

# Example usage
try:
    user = User(name="Alice", email="[email protected]", age=25)
    print("Validated:", user)
except ValidationError as e:
    print("Validation Error:", e.json())
python
Login to see the comments