-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Assert at end of if statement does not help mypy value inference #3431
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
I think this is something specific to from typing import Union
x: Union[str, int]
if isinstance(x, int):
# do something at runtime
assert isinstance(x, str)
reveal_type(x) # Revealed type is 'builtins.str' |
This works as expected: from typing import Optional
def f(s: Optional[str]):
if s is None:
s = ''
reveal_type(s) # Revealed type is 'builtins.str' However, this fails: from typing import Optional, Any
def f(s: Optional[str], a: Any):
if s is None:
s = a
reveal_type(s) # Revealed type is 'Union[builtins.str, builtins.None]' Assignment of from typing import Optional, Any
def f(s: Optional[str], a: Any):
if s is None:
s = a
reveal_type(s) # Revealed type is 'Union[builtins.str, builtins.None]' A potential fix would be to make an assignment of from typing import Optional, Any
def f(s: Optional[str], a: Any):
if s is None:
s = a
reveal_type(s) # Maybe the inferred type should be just str? A less ad hoc option would be to infer |
I think mypy's current behaviour is good |
No mypy's behavior is not good, but after some thinking it seems to me it is likely a duplicate of #3724 (that I just re-opened), or at least they have the same root cause. |
While working on making zulip pass with
mypy --strict-optional
, I ran into the following piece of code. Mypy was essentially saying that message.get_realm() was not guaranteed to work ("Not all parts of the union have get_realm() method", or somesuch.)Let's assume, at least for here, that the get() call will never return None. I tried the following change, but mypy was still giving the exact same error:
However, with this change, mypy was now happy with the code snippet:
The two asserts clearly have the same code behavior of making it impossible for
message
to beNone
when we reach therendered_content = ...
line, but mypy only understands that currently (version 5.111) for the last code snippet only. Opening this bug report for discussion of that.(Feel free to change the title of this bug report to a more meaningful / better one.)
The text was updated successfully, but these errors were encountered: