[mypyc] Use correct rtype for variable with inferred optional type#15206
[mypyc] Use correct rtype for variable with inferred optional type#15206JukkaL merged 2 commits intopython:masterfrom
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. |
JukkaL
left a comment
There was a problem hiding this comment.
Thanks for the fix! Looks good. Left some suggestions about tests.
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