pydantic typecasting


Did you know?

Pydantic uses typecasting.

That means that it tries to convert provided values to their expected types if it's possible.

Examples👇

import datetime

from pydantic import BaseModel


class Location(BaseModel):
    city: str
    country: str


class Measurement(BaseModel):
    temperature: float
    measured_at: datetime.datetime
    location: Location


print(
    Measurement(
        temperature=10,
        measured_at="2021-04-16T21:15:03.000012",
        location={"city": "London", "country": "UK"},
    )
)

"""
temperature=10.0 measured_at=datetime.datetime(2021, 4, 16, 21, 15, 3, 12) location=Location(city='London', country='UK')
"""

print(
    Measurement(
        temperature=10.0,
        measured_at="2021-04-16T21:15:03",
        location=Location(city="London", country="UK"),
    )
)

"""
temperature=10.0 measured_at=datetime.datetime(2021, 4, 16, 21, 15, 3) location=Location(city='London', country='UK')
"""

print(
    Measurement(
        temperature=10,
        measured_at="16186000528",
        location=[("city", "London"), ("country", "UK")],
    )
)

"""
temperature=10.0 measured_at=datetime.datetime(2021, 4, 16, 19, 15, 28, tzinfo=datetime.timezone.utc) location=Location(city='London', country='UK')
"""