-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Mypy could not do condition inference #19029
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
Hello, I want to solve this problem. Can I? |
PRs are welcome but this is likely a complicated feature to add. Also this issue is probably a duplicate but I haven't looked. |
I think this is a duplicate of #9229. This feature is formally called "aliased conditional expressions". The first time I saw it implemented was in the TypeScript compiler in 2021. I later implemented it in pyright. As Jelle said, it's tricky to get this feature right because a static analyzer must prove that there is no statement that can invalidate the condition on any code path between the assignment of the condition variable and its later use for narrowing. Consider the following three examples: def func1(x: int | None):
is_int = x is not None
for _ in range(2):
if is_int: # Safe to narrow x to `int`
reveal_type(x) # int
def func2(x: int | None):
is_int = x is not None
for _ in range(2):
if is_int: # Not safe to narrow x to `int`
reveal_type(x) # int | None
x = None
def func3(x: int | None):
is_int = x is not None
for _ in range(2):
if is_int: # Not safe to narrow x to `int`
reveal_type(x) # int | None
is_int = True |
Thanks |
1 similar comment
Thanks |
Bug Report
To Reproduce
The min sample:
Expected Behavior
It should pass the test
Actual Behavior
The only way to avoid this error output is to replace each
is_not_none
withsource is not None
. It makes the code silly sometimes, and forces me to revamp the logic just for mypy which is a totally waste of my time.Your Environment
mypy.ini
(and other config files): n/aThe text was updated successfully, but these errors were encountered: