Skip to content

Incorrect type reification on optional union attribute in conditional #7884

Description

@elprans

Repro:

bug.py:

from __future__ importannotationsfromtypingimport*classB:
passclassA:
name: Optional[Union[str, B]]
deffoo(a: A):
ifisinstance(a.name, str):
passelifisinstance(a.name, B):
passelse:
raiseAssertionErrorbar(a.name)
defbar(arg: Union[str, B]):
pass

mypy incorrectly reports an error:

bug.py:22: error: Argument 1 to "bar" has incompatible type "object"; expected "Union[str, B]"

Interestingly, when a.name is aliased with another name, the issue disappers, i.e. the following is checked without an issue:

ok.py:

from __future__ importannotationsfromtypingimport*classB:
passclassA:
name: Optional[Union[str, B]]
deffoo(a: A):
a_name=a.nameifisinstance(a_name, str):
passelifisinstance(a_name, B):
passelse:
raiseAssertionErrorbar(a_name)
defbar(arg: Union[str, B]):
pass

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions