Runtime validation in type annotations

8 points by natfu


rtpg

After using a lot of these I find myself really disliking the "type annotation"-based APIs like Pydantic.

Way back when, before django-stubs, we got typing for our Django models working through a simple trick: making models.CharField and friends descriptors.

Doing that means you don't have to do anything magical, you don't have to "lie" at some level with stuff like foo: int = MagicalIntFieldConfigurationObject(option_1='a'), and it lets inference work in a decently straightforward way.

At a higher level I tend to find runtime validation of type sigs to be something brought by people ignoring the "point" of all this type theory. The point of the type theory is that if you have foo(): int, then you don't need to validate the return value of foo()! And when you do value = foo(); bar(value) you don't need to re-validate that value is an integer!

You still need to validate untrusted input, but Pydantic will check that, say, 4 is an integer when you pass it in, despite you having proven at a static level that the literal 4 is an integer.

And when you get to more complicated validation the APIs quickly become way uglier than older school model validation libs in Python.