python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
17.85k stars 2.74k forks source link

Experimental: allow inline/anonymous TypedDicts #17457

Open ilevkivskyi opened 2 days ago

ilevkivskyi commented 2 days ago

Fixes https://github.com/python/mypy/issues/9884

I was always a bit skeptical about this thing, since it feels more like TypeScript than Python, but it is second most upvoted issue. Also (this specific) implementation is like 60 lines of code plus tests, so why not.

I know there is no PEP etc., but IMO this syntax is obvious and it just works. cc @JukkaL

github-actions[bot] commented 2 days ago

Diff from mypy_primer, showing the effect of this PR on open source code:

steam.py (https://github.com/Gobot1234/steam.py)
- steam/http.py:901: error: Invalid type comment or annotation  [valid-type]
github-actions[bot] commented 2 days ago

Diff from mypy_primer, showing the effect of this PR on open source code:

steam.py (https://github.com/Gobot1234/steam.py)
- steam/http.py:901: error: Invalid type comment or annotation  [valid-type]
bzoracler commented 1 day ago

While I like the elegance of the bare literal dict, the problem is that it doesn't compose well with union expressions in type annotation contexts.

Without a __future__.annotations guard, a union of two bare literal dicts in a runtime type annotation context will result in what looks like a type intersection instead of a union,

class A:
    a: {"int": int} | {"str": str}
>>> A.__annotations__
{'a': {'int': <class 'int'>, 'str': <class 'str'>}}

and a union with most other objects would result in a runtime error (e.g. {"str": str} | list[int]).

Maybe (before a PEP etc is proposed for the actual syntax), unions should be banned from being composed with bare literal dicts?