Pydantic is a Python library used for data validation and settings management. It allows you to define data schemas using Python annotations and then automatically validates input data against those schemas. Here are some features of Pydantic along with examples:

  1. Model Declaration:
from pydantic import BaseModel

class User(BaseModel):
username: str
email: str
age: int

2. Data Validation:

user_data = {"username": "john_doe", "email": "[email protected]", "age": 25}
user = User(**user_data)

3. Default Values:

class Item(BaseModel):
name: str = "Unknown"
price: float = 0.0

4. Data Parsing:

data = {"name": "Product", "price": "25.5"}
item = Item.parse_obj(data)

5. Custom Validators:

from pydantic import validator

class UserModel(BaseModel):
username: str
email: str

@validator("username")
def username_alphanumeric(cls, v):
assert v.isalnum(), "must be alphanumeric"
return v

6. Dependency Injection:

from pydantic import BaseSettings 
class Settings(BaseSettings): 
api_key: str 
settings = Settings(_env_file=".env")

 

Pydantic helps avoid input errors, improves code clarity, and simplifies application configuration management. With these features, you can ensure that the data used in your application meets expectations, reducing potential bugs and enhancing application security.


Discover more from Susiloharjo

Subscribe to get the latest posts sent to your email.

Discover more from Susiloharjo

Subscribe now to keep reading and get access to the full archive.

Continue reading