python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.22k stars 2.78k forks source link

type is not recalculated when it was previously a List[Any] #8540

Open dpinol opened 4 years ago

dpinol commented 4 years ago

def get_any() -> Any: return {}

def fun(message_json) -> int: messages = [get_any()] messages = get_any() if not isinstance(messages, list): print(messages) return 2

* What is the actual behavior/output?

:12 error: Statement is unreachable [unreachable] print(messages)

* What is the behavior/output you expect?
I would expect one the following:
a) Either I get an error because "messages" is reassigned to Any afetr it was a list in the previous line
b) Or I don't get the "unreachable" error because before the "if", "messages" can indeed not be a list

Curiously with the code below, I don't get any error

from typing import Any

def get_any() -> Any: return {}

def fun(message_json) -> int: messages = [3] # <=== only this line changes messages = get_any() if not isinstance(messages, list): print(messages) return 2



* What are the versions of mypy and Python you are using?
0.770 (with 0.761 I got the same error message but with "misc" code)

* What are the mypy flags you are using? (For example --strict-optional)
--show-error-codes  --warn-unreachable 
JukkaL commented 4 years ago

The issue here is that an assigning an Any values does not update the inferred type of messages. The current behavior is somewhat incorrect, but it increases type checking precision in the common case. We could try out the change on semantics and estimate whether the precision loss is small enough to make this worthwhile.

The second example not generating error seems to be a separate issue.

Sometimes --allow-redefinition would help (but not in the above examples).