-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
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
[mypyc] Use correct rtype for variable with inferred optional type #15206
Conversation
```python def f(b: bool) -> None: if b: y = 1 else: y = None f(False) ``` On encountering y = 1, mypyc uses the expression type to determine the variable rtype. This usually works (as mypy infers the variable type based on the first assignment and doesn't let it change afterwards), except in this situation. NameExpr(y)'s type is int, but the variable should really be int | None. Fortunately, we can use the Var node's type information which is correct... instead of blindly assuming the first assignment's type is right.
Is there a reason to limit combining infered types across branches to def test(flag: bool):
if flag:
x = 1
else:
x = ""
reveal_type(x)
# mypy: builtins.int
# pyright: Literal[1, ""] I assume this might be a big change for mypy but when adding a special case for |
@twoertwein that is a question for the mypy maintainers. I'm part of the core team, but I only work on mypyc. This PR simply fixes mypyc (the compiler) to do the right thing when mypy infers a combined type across branches (and not generate code that immediately crashes). In what situations mypy infers a combined type is not within the domain of this PR. Edit: found the relevant mypy issue -> #6233. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Thanks for the fix! Looks good. Left some suggestions about tests.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Looks good now, thanks!
On encountering y = 1, mypyc uses the expression type to determine the
variable rtype. This usually works (as mypy infers the variable type
based on the first assignment and doesn't let it change afterwards),
except in this situation.
NameExpr(y)'s type is int, but the variable should really be int | None.
Fortunately, we can use the Var node's type information which is
correct... instead of blindly assuming the first assignment's type is
right.
Fixes mypyc/mypyc#964