Usage with mypy
Pydantic works with mypy provided you use the "annotation only" version of required fields:
from datetime import datetime from typing import List, Optional from pydantic import BaseModel, NoneStr class Model(BaseModel): age: int first_name = 'John' last_name: NoneStr = None signup_ts: Optional[datetime] = None list_of_ints: List[int] m = Model(age=42, list_of_ints=[1, '2', b'3']) print(m.age) # > 42 Model() # will raise a validation error for age and list_of_ints
(This script is complete, it should run "as is")
You can also run it through mypy with:
mypy \ --ignore-missing-imports \ --follow-imports=skip \ --strict-optional \ pydantic_mypy_test.py
For your code to pass with
--strict-optional you need to to use
Optional or an alias of
for all fields with
None default, this is standard with mypy.
Pydantic provides a few useful optional or union types:
If these aren't sufficient you can of course define your own.