I enjoy using Python, but the dynamic typing makes me itch.
This week I came across Pydantic, a great library that goes some way towards scratching this long-standing itch.
Pydantic allows you to inherit from its BaseModel
class in your own classes; Pydantic will then try its best to parse the given input into the type you have specified in your type hints.
from pydantic import BaseModel
from app.models.v1.author import Author
class Book(BaseModel):
id: str
name: str
isbn: str
author: Author
genre: str
read_count: int
In my example above, here - if the client passes a float type 5.0
, or string type "5"
into my read_count
field - whilst they aren't of the integer type I originally had in mind for my class, it's all cool.
Pydantic will parse this into the specified integer type using the normal Python type casting rules. 👌
This saves writing a load of custom parsing logic.
But if the client tries to give me a "five"
, it's game-over... 💥
pydantic.error_wrappers.ValidationError: 1 validation error for Book
read_count
value is not a valid integer (type=type_error.integer)
I really like this.
Type hints are great, but Pydantic lets us go a little further and actually put them to work. 💪