Python Type Checker Comparison: Empty Container Inference
48 points - last Wednesday at 1:45 PM
SourceComments
Boxxed today at 6:54 PM
My favorite part about the type annotations in python is that it steers you into a sane subset of the language. I feel like it's kind of telling that python is this super dynamic language but the type annotations aren't powerful enough to denote all that craziness.
jez today at 6:54 PM
A more complicated version of this problem exists in TypeScript and Ruby, where there are only arrays. Pythonβs case is considerably simpler by also having tuples, whose length is fixed at the time of assignment.
In Python, `x = []` should always have a `list[β¦]` type inferred. In TypeScript and Ruby, the inferred type needs to account for the fact that `x` is valid to pass to a function which takes the empty tuple (empty array literal type) as well as a function that takes an array. So the Python strategy #1 in the article of defaulting to `list[Any]` does not work because it rejects passing `[]` to a function declared as taking `[]`.
tl2do today at 9:30 PM
Is there a compile-to-Python language with built-in type safety, similar to how TypeScript transpiles to JavaScript? I'm aware of Mojo and mypyc, but those compile to native code/binaries, not Python source.
Sinidir today at 9:47 PM
In the example given in the article i think the correct behavior would have been to infer the type backwards from the return type of the function. Is that not why mypy actually errors here?
loevborg today at 7:12 PM
FWIW, Typescript is using Strategy 2: https://www.typescriptlang.org/play/?#code/GYVwdgxgLglg9mABM...
I'm a bit confused by the fact that the array starts out typed as `any[]` (e.g. if you hover over the declaration) but then, later on, the type gets refined to `(string | number)[]`. IMO it would be nicer if the declaration already showed the inferred type on hover.
brainzap today at 9:56 PM
In early typescript I was too lazy and just set an inital value and then zero the list
electroglyph today at 10:19 PM
my wishlist for pyrefly: when using decorated functions, show the underlying type hints instead of the decorators
IshKebab today at 6:50 PM
I think it would be worth mentioning that in normal use (strict mode) Pyright simply requires you to add type annotations to the declaration. Occasionally mildly annoying but IMO it's clearly the best option.
curiousgal today at 6:33 PM
I can't help but find type hints in python to be..goofy? I have a colleague who has a substantial C++ background and now working in python, the code is just littered with TypeAlias, Generic, cast, long Unions etc.. this can't be the way..
nimbus-hn-test today at 9:23 PM
Enforcing explicit annotations in strict mode is a productivity multiplier. It prevents `list[Unknown]` from polluting the rest of the codebase, which is much harder to fix later.