pydantic validates your inputs, or does it?
TL;DR¶
🎊 pydantic
calls itself the most widely used data validation library for Python
😧 Yet, it does not validate default values, nor assignments by default. That's ... unexpected
Background¶
pydantic
is a Python library that tries to bring type-safety to Python. Rather than type hints (it may be true, but doesn't have to be), pydantic
will validate an input. An example:
from pydantic import BaseModel
Â
class Test(BaseModel):
  foo: str
Â
t = Test(foo=[1,2,3]) # Raises a ValidationError
Let's have some fun with pydantic
validation¶
However, this works without problem: Â
 Equally, this also works: Âfrom pydantic import BaseModel
Â
class Test(BaseModel):
  foo: str
Â
t = Test(foo="1")
t.foo = [1,2,3]
pydantic
argues that this is performance plus backwards compatibility, at least according to this Github issue. I disagree. The reason to use pydantic
is type-safety.
And being able to violate the type-safety in the default settings  is not expected behavior.
Â
Alas, there is a setting so solve it:
Â
Â
As you would expect, the validate_default
validates the default values, while validate_assignment
validates the assignment.