Re:Python 3 Types in the Wild
by goodoldneon on Friday March 18, 2022 @11:27AM
(#30723495)
Python does ignore them at runtime, but as long as you're validating your inputs (e.g. using Pydantic for HTTP request validation) then you can trust that the static types are truthful
[ Parent
| on HN ]
Re:Python 3 Types in the Wild
by lelandbatey on Friday March 18, 2022 @04:14PM
(#30726965)
I want to emphasize for folks reading: if you want actual type enforcement and you want that type enforcement with minimum boilerplate, Pydantic is a fantastic option (I'm sure there are others as well). It's a great library that's totally use-agnostic (it's not HTTP specific, you can use it for whatever) and quite tight. Caveats are that it uses runtime validation to enforce types so there's a performance cost, but it's a performance hit that is mostly eclipsed by all the other huge performance hits that litter your typical Python implementation.
Pydantic is amazing!
Re:Python 3 Types in the Wild
by mixmastamyk on Saturday March 19, 2022 @01:28PM
(#30735674)
IIRC, pydantic was quite big and I chose typeguard instead for a smaller project. Might be an option.
Re:Python 3 Types in the Wild
by musingsole on Friday March 18, 2022 @01:11PM
(#30724802)
> trust that the static types are truthful
That's often a mistake even in typed languages like typescript. Satisfying a static type analyzer isn't enough. Real data is whatever it is going to be. If your types are meaningless at runtime, you can easily encounter type mismatches.
Static typing as implemented in typescript and python type hints is a tool for engineers instead of a tool for systems.
Re:Python 3 Types in the Wild
by roywiggins on Friday March 18, 2022 @01:21PM
(#30724932)
The types are usually ignored, but not entirely erased- Pydantic uses type hints to do validation at runtime, so if you construct a Pydantic object with invalid data it will throw an error, so eg
foo=PydanticFoo(**request.json())
Will try and validate a json request against the implied schema provided by the type hints on PydanticFoo while constructing it and will throw if it fails.
Re:Python 3 Types in the Wild
by goodoldneon on Friday March 18, 2022 @02:03PM
(#30725469)
You missed my point. If you validate input, then the static types are representative of runtime types
Re:Python 3 Types in the Wild
by musingsole on Friday March 18, 2022 @03:11PM
(#30726276)
Ack, so I did :P