Pydantic for Data Validation and Type Conversion
Use Python type hints to validate input, convert values, and describe nested data with Pydantic.
On this page
Pydantic for Data Validation and Type Conversion
Unexpected input and type errors can turn a small Python script into a lot of defensive code. Pydantic uses type hints to validate and convert data for you.
Install Pydantic
pip install pydanticNOTE
See the Pydantic installation guide for more setup options.
Basic usage
The usual starting point is a model. Suppose we have a class called User.
from pydantic import BaseModel
class User(BaseModel):
id: int
name: str
signup_ts: str | None = None
friends: list[int] = []
user = User(id=123, name='John Doe', signup_ts="2024-05-01T12:00", friends=[1, 2, 3])
print(user)
print(user.id)
print(user.dict()) # 轉成 dictionaryAutomatic type conversion
Pydantic can convert values to the declared type when it knows how. Here's an example.
user = User(id='123', name='John Doe', signup_ts=None, friends=[1, '2', b'3'])
print(user)# id=123 name='John Doe' signup_ts=None friends=[1, 2, 3]Pydantic attempts the conversion and raises a ValidationError if it fails.
'123'becomes123.[1, '2', b'3']becomes[1, 2, 3].
Validation errors
What happens when a value cannot be converted?
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
signup_ts: str | None = None
friends: list[int] = []
try:
User(id='not-an-int', name='John Doe')
except ValidationError as e:
print(e)# 1 validation error for User
# id
# Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value='not-an-int', input_type=str]
# For further information visit https://errors.pydantic.dev/2.11/v/int_parsingNested models
For more complex data, you can use one model as the field type of another.
class Address(BaseModel):
street: str
city: str
class User(BaseModel):
name: str
address: Address
u = User(name="Alice", address={"street": "1st Street", "city": "Metropolis"})
print(u.address.street)# 1st StreetDumping and copying models
from pydantic import BaseModel, ValidationError
class User(BaseModel):
id: int
name: str
user = User(id=123, name='John Doe')
print(user.model_dump()) # Dictionary
print(user.model_dump_json()) # JSON string
new_user = user.model_copy(update={'name': 'Jane Doe'})
print(new_user)# {'id': 123, 'name': 'John Doe'}
# {"id":123,"name":"John Doe"}
# id=123 name='Jane Doe'NOTE
The older dict(), json(), and copy() methods are deprecated. Pydantic v2 uses model_dump(), model_dump_json(), and model_copy().
Field configuration
| What you want to do | How to do it |
|---|---|
| Require a field | Field(...) |
| Set a default | Field(default_value) |
| Restrict a numeric range | gt=, ge=, lt=, le= |
| Limit string or list length | min_length=, max_length= |
| Describe the field in API docs | title=, description= |
| Accept input under a different name | alias="other_name" |
| Exclude a field from output | exclude=True |
| Compute a default for each instance | default_factory=... |
from pydantic import BaseModel, Field
class User(BaseModel):
id: int = Field(..., gt=0, lt=9999) # 必填且介於0-9999之間
name: str = Field(..., Harry) # 必填且default value是HarryClosing note
These model definitions also work well with FastAPI, where they can describe request data and drive validation.