Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Union types for dict keys are not inferred in union context #6079

Open
bryanforbes opened this issue Dec 17, 2018 · 1 comment
Open

Union types for dict keys are not inferred in union context #6079

bryanforbes opened this issue Dec 17, 2018 · 1 comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code needs discussion priority-1-normal topic-join-v-union Using join vs. using unions topic-union-types

Comments

@bryanforbes
Copy link
Contributor

mypy: 0.650
Python: 3.7.1

I'm not sure if this is a bug or a new feature, however the following code is unexpected (in my mind, especially coming from TypeScript):

d = {"1": 2, 3: 4}
reveal_type(d)  # builtins.dict[builtins.object*, builtins.int*]

I would have expected mypy to infer the type of d as builtins.dict[Union[builtins.str*, builtins.int*], builtins.int*].

@ilevkivskyi
Copy link
Member

The situation is more complex than that. The fact mypy doesn't infer unions for joins is expected. What is not expected is that mypy doesn't infer unions in a union context. Here are better examples:

x: List[Union[int, str]] = [42, 'hi']  # OK
y: Union[List[Union[int, str]], List[int]] = [42, 'hi'] # Incompatible types in assignment because of `List[object]`

Our treatment of unions for inference is not very principled, but doing it right might be hard. And TBH I don't have any clear idea.

A bit more details: using the external context we infer constrains against every item of the outer union that leads to unsatisfiable constraints. Then falling back to inner context causes us to infer a join which is an object. Note that putting all constraints into the same bin will not help here.

@ilevkivskyi ilevkivskyi changed the title Union types for dict keys are not inferred Union types for dict keys are not inferred in union context Dec 18, 2018
@ilevkivskyi ilevkivskyi added bug mypy got something wrong needs discussion priority-1-normal false-positive mypy gave an error on correct code topic-union-types labels Dec 18, 2018
@JelleZijlstra JelleZijlstra added the topic-join-v-union Using join vs. using unions label Mar 19, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong false-positive mypy gave an error on correct code needs discussion priority-1-normal topic-join-v-union Using join vs. using unions topic-union-types
Projects
None yet
Development

No branches or pull requests

3 participants