- Notifications
You must be signed in to change notification settings - Fork282
Why does a dictionary union cause a type checking failure?#2104
-
https://mypy-play.net/?mypy=latest&python=3.12&gist=2c48503ebd2236fad252604292710529 Why does case |
BetaWas this translation helpful?Give feedback.
All reactions
Replies: 1 comment 1 reply
Uh oh!
There was an error while loading.Please reload this page.
Uh oh!
There was an error while loading.Please reload this page.
-
Nice question :) One needs to think here about assignability andwhen 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: fromtypingimportcastb:JSON=cast("dict[str, str]", {'':''})# errord: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 |
BetaWas this translation helpful?Give feedback.
All reactions
-
There are some additional subtleties here. To understand this behavior, you need to first understandbidirectional type inference. Normally, a static type checker infers the type of expression Bidirectional type inference can be applied to a variety of expression forms including literal container expressions (lists, sets, dicts, tuples), as well as comprehensions, assignments, unary operators, lambdas, and call expressions. In general, it cannot be applied to binary operators like In your example Extending your example, |
BetaWas this translation helpful?Give feedback.
All reactions
👍 1