Closed
Description
Not sure if this has already been discussed; I couldn't find an exact duplicate although #1094 and #1174 are similar. I have code like this:
try:
x = 3
reveal_type(x) # expect int
except SomeError:
x = None
reveal_type(x) # expect None
else:
reveal_type(x) # expect int
# (do things that assume that x is an int)
reveal_type(x) # expect Union[int, None]
but mypy gives an error the assignment in the except block and doesn't infer the union. I tried adding an explicit # type: Optional[int]
to the first assignment, but then mypy no longer recognizes that x is a non-Optional int in the else block. I ran into this with a try block but I assume an if block would get the same result.
Not sure how easy this is to change or if it affects some other behavior in mypy. I have implemented similar logic in the past by inferring types separately from assignments in the two branches and then unifying the two.