3 ms·
Coming back from TypeScript to Python, I found that most recent (3.10+) typing annotation shorthands are pretty succinct, and running mypy at all times really h
by strogonoff 4y ago
Coming back from TypeScript to Python, I found that most recent (3.10+) typing annotation shorthands are pretty succinct, and running mypy at all times really helps cut down on runtime errors.
My recipe:
— annotate variables, attributes, arguments and return values;
— run a good type linter (we use mypy) at all times;
— never pass around generic dictionaries: use dataclasses[0], TypedDicts, etc. instead.
That way you define a subclass inheriting from, say, TypedDict and declare that your function only takes that subclass. After that, you’ll get a loud error if you pass any dictionary that doesn’t match the spec (missing keys, wrong values, etc.)—ideally, right in your IDE.
(To reiterate, this would be a pointless exercise if you don’t lint all the time; most IDEs support this.)
[0] You can additionally use them with Pydantic, which can validate data at runtime at a cost of some performance overhead.