Skip to content

Union should be automatically inferred when assignment occurs in multiple branches #2611

Closed
@JelleZijlstra

Description

@JelleZijlstra

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.

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions