-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Better message when inferred variable type conflicts with later use #2529
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
Comments
Mypy infers types roughly from top to bottom. This usually makes reasoning about inferred types easier and the implementation is also relatively straightforward. However, there are cases like your example this has undesirable results. You can add a type annotation to make the error go away: from typing import Union, Dict, List
def g() -> List[Union[str, int]]:
x = ['a'] # type: List[Union[str, int]]
x += [1]
return x
def f() -> Dict[str, Union[str, int]]:
d = {'a': 'a'} # type: Dict[str, Union[str, int]]
d['b'] = 1
return d Modifying type inference to take the return type into consideration in cases like this would be hard and would complicate the relatively simple and predictable (once you understand a few principles) model that mypy currently uses. However, it might be useful to detect some cases like this and give a better error message. Potential better message:
|
As it's unlikely that type inference will change for now, I'll update the title to consider a better error message. |
I will take a look at this. |
Should this note only cover the case when the object type conflicts with the return type or should it also cover the following:
which currently only outputs
I am planning on proceeding with only enhancing the message when it conflicts with the return and not cover the above case. |
Uh oh!
There was an error while loading. Please reload this page.
If you can come up with a better name for this issue, please let me know, this one is poor. The naming difficulty also lead to difficulty searching to see if this already existed, so apologies in advance if this is a duplicate issue.
When running this code through the typechecker:
I get this output:
With both these functions, mypy is assuming the type on assignment, then having type errors due to conflicts with the explicitly declared return type.
Surely there should be a way to correctly infer the original type based on the return type?
The text was updated successfully, but these errors were encountered: