8000 Error when assigning a ternary with an empty collection to a union type variable · Issue #7780 · python/mypy · GitHub
[go: up one dir, main page]

Skip to content

Error when assigning a ternary with an empty collection to a union type variable #7780

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

Closed
raphj opened this issue Oct 23, 2019 · 4 comments · Fixed by #7892
Closed

Error when assigning a ternary with an empty collection to a union type variable #7780

raphj opened this issue Oct 23, 2019 · 4 comments · Fixed by #7892

Comments

@raphj
Copy link
raphj commented Oct 23, 2019

Hello,

the following code:

from typing import List, Union
import sys
p : Union[int, List[int]] = 1 if len(sys.argv) else []

incorrectly generates the following error:

t.py:3: error: Incompatible types in assignment (expression has type "Union[int, List[<nothing>]]", variable has type "Union[int, List[int]]")

Adding an integer in the list makes the error disappear. I first observed this issue with a dictionary:

from typing import Dict, Union
import sys
p : Union[int, Dict[int, int]] = 1 if len(sys.argv) else {}

Error:

t.py:3: error: Incompatible types in assignment (expression has type "Union[int, Dict[<nothing>, <nothing>]]", variable has type "Union[int, Dict[int, int]]")

It seems <nothing> should be matched with any type in type parameters in unions.

@raphj raphj changed the title Error when assigning a ternary to a union type variable Error when assigning a ternary with an empty collection to a union type variable Oct 23, 2019
@nautics889
Copy link
Contributor

Please, take a look at this topic. Perhaps mypy should consider an empty list like an object that fits List[int], but unfortunately it doesn't.
I think the best solution for you would be use Any type:

p : Union[int, List[Any]] = 1 if len(sys.argv) else []

@raphj
Copy link
Author
raphj commented Oct 24, 2019

I worked around this issue by getting rid of the ternary condition and using a regular if statement instead.

@ilevkivskyi
Copy link
Member

Another possible workaround could be using a covariant collection like Sequence. I however think mypy can do better here. We can probably pass through the type context in case of the ternary expressions.

@ilevkivskyi
Copy link
Member

This actually may be not hard to fix, one just needs to update the logic in mypy/checkexpr.py in visit_conditional_expr() to try the original context ctx for the else expression.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

3 participants
0