News for hackers. Stuff that matters.
Re:Writing Python like it's Rust by NeutralForest on Sunday May 21, 2023 @05:56AM (#36019375)
A typical pain point where type hinting fails in Python is with list of some types, it can't be enforced by the language without more checks.

For example, you can't do:

if isinstance(x, list[int])

though it would be super useful

Re:Writing Python like it's Rust by mejutoco on Sunday May 21, 2023 @08:53AM (#36020400)
You need to use mypy or similar to not check it at runtime:

    els: List[int]
To test it at runtime you can use typeguard s @typechecked annotation. For convenience you can also use Pydantic.
Re:Writing Python like it's Rust by NeutralForest on Sunday May 21, 2023 @10:31AM (#36021256)
Yes I know, I'm just pointing out that you need additional tool to check that.
Re:Writing Python like it's Rust by smnrchrds on Sunday May 21, 2023 @03:44PM (#36024127)
I didn't know about typeguard. Thank you for the recommendation!

How do you do this in Pydantic though?

Re:Writing Python like it's Rust by mejutoco on Sunday May 21, 2023 @05:52PM (#36025012)
For this example pydantic would be overkill, but you can use with it class definitions that follow standard python class hints, with additional utilities like YourClass.parse_obj(d) that parse a dict and throw a validation error if it does not match, with mostly standard type annotations.

It can also be used to generate openapi swagger files from the types and things like that.