Why does a dictionary union cause a type checking failure? #2104
Replies: 1 comment 1 reply
-
Nice question :) One needs to think here about assignability and when types are assigned / inferred, this involves which kind of python statements you are using. Here are some more interesting points to look at: b: JSON = reveal_type({'': ''}) You might expect that the revealed type is Now lets look at: from typing import cast
b: JSON = cast("dict[str, str]", {'': ''}) # error
d: dict[str, str] = {}
b = d # error I hope you can see why this fails. Because of invariance, you cannot assign a Lastly lets check out: c: JSON = {'': ''} | cast("JSON", {}) # OK Why is this fine and |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
https://mypy-play.net/?mypy=latest&python=3.12&gist=2c48503ebd2236fad252604292710529
Why does case
c
fail whilea
andb
are okay?Beta Was this translation helpful? Give feedback.
All reactions