You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
At the last line of the example, I expected mypy to infer that the except branch hadn't been taken, and therefore x was of type int, just as it is at the end of the try branch.
Actual Behavior
test.py:17: error: Unsupported operand types for + ("None" and "int") [operator]
test.py:17: note: Left operand is of type "Optional[int]"
Your Environment
Mypy version used: 0.991 (compiled: yes)
Mypy command-line flags: none
Mypy configuration options from mypy.ini (and other config files): none
Python version used: 3.10.7
The text was updated successfully, but these errors were encountered:
#[...]try:
x=maybe_int()
x+=1# With this line added here...exceptValueError:
x=Noneelse:
x+=1# ...there's no longer a mypy error on this line!
I wanted to double-check my intuition that x += 1 should be valid at the end of the try block (where x should be of type int). Of course, it is -- but not only that, it also causes the inference in the else block to work as I'd expected. I can't immediately see why that would be.
classFoo:
x=1defmain() ->None:
try:
foo=Foo()
reveal_type(foo) # note: Revealed type is "Foo"except:
foo=Nonereveal_type(foo) # note: Revealed type is "None"else:
reveal_type(foo) # note: Revealed type is "Union[Foo, None]"print(foo.x) # error: Item "None" of "Optional[Foo]" has no attribute "x"
this is with mypy version 1.8.0 on python 3.9.18
what's weird is that the assignment in the except clause is only allowed if it is None. If, for example, it was
except:
foo=1
then mypy throws Incompatible types in assignment (expression has type "int", variable has type "Foo")
which I guess could be a valid error here. Though, since the try(+else) and except clauses are mutually exclusive I'd argue it's fine to allow assignment with different types (and it already kinda does allow that by allowing you to set foo to Foo() in the try clause and then None in the except clause but I'm guessing there's some special handling for None.)
Bug Report
In the
else
branch of a try-except-else, mypy ought to be able to infer that noexcept
branch was taken.To Reproduce
https://mypy-play.net/?mypy=latest&python=3.11&gist=306f5b87e1b2eadc3f7692718a21f6b5
Expected Behavior
At the last line of the example, I expected mypy to infer that the
except
branch hadn't been taken, and thereforex
was of typeint
, just as it is at the end of thetry
branch.Actual Behavior
Your Environment
mypy.ini
(and other config files): noneThe text was updated successfully, but these errors were encountered: