What is Pydantic?
- Pydantic is a data validation library aimed to solve Python’s dynamic typing problem!
- Similar to data-classes and type hinting (which also solve dynamic typing) but more powerful
Installation,
pip install pydantic
Pydantic vs Dataclass
Features | Pydantic | Dataclass |
---|---|---|
Type Hints | yes | yes |
Data Validation | yes | no |
Serialization | yes | partial |
Built-In | no | yes |
Usage
from pydantic import BaseModel, EmailStr
class User(BaseModel):
name: str
email: EmailStr
account_id: int
# Instatiation
user1 = User(
name="nish",
email="nish@google.com",
account_id=1
)
# Instatiate from an existing object
user_data = {
'name': 'nish',
'email': 'nish@google.com',
'account_id': 1
}
user2 = User(**user_data)
# Instantiate from a JSON string
json_str = '{"name": "nish", "email": "nish@google.com", "account_id": 1}'
user3 = User.parse_raw(json_str)
Custom validators
- Pydantic let’s you create custom validators using the
@validator
decorator - For example say we want all
account_id
s to be a positive integer,from pydantic import BaseModel, EmailStr, validator class User(BaseModel): name: str email: EmailStr account_id: int @validator('account_id') def validate_account_id(cls, value): if value <= 0: raise ValueError(f"account_id must be positive: {value}") return value user = User(name="Nish", email="nish@gmail.com", account_id=1) print(user)