Fix isinstance with type aliases to PEP 604 unions#17371
Fix isinstance with type aliases to PEP 604 unions#17371hauntsaninja merged 4 commits intopython:masterfrom
Conversation
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
This comment has been minimized.
|
According to mypy_primer, this change doesn't affect type check results on a corpus of open source code. ✅ |
JukkaL
left a comment
There was a problem hiding this comment.
What about old-style unions? They work at runtime:
>>> from typing import Union
>>> isinstance(1, Union[int, str])
True
It's also okay to only support PEP 604 unions for now.
|
Note those only work with |
|
I'll take a look at supporting old-style unions, but in another PR. It doesn't seem to be nearly as popular a feature request and it would require monkeypatching typeshed or doing more isinstance special casing: python/typeshed#12137 |
|
This also fixes #13810 |
|
@hauntsaninja Unfortunately it seems this fix doesn't extend to the case where the type alias is defined in another module: Given from typing import TypeAlias
IntOrStr: TypeAlias = int | str
assert isinstance(1, int | str)
assert isinstance(1, IntOrStr)And from a import IntOrStr
assert isinstance(1, int | str)
assert isinstance(1, IntOrStr)I get the following output: $ mypy --version
mypy 1.11.0 (compiled: yes)
$ mypy --strict a.py
Success: no issues found in 1 source file
$ mypy --strict b.py
b.py:4: error: Parameterized generics cannot be used with class or instance checks [misc]
b.py:4: error: Argument 2 to "isinstance" has incompatible type "<typing special form>"; expected "_ClassInfo" [arg-type]
Found 2 errors in 1 file (checked 1 source file)The issue seems to be that |
Fixes #12155, fixes #11673, seems pretty commonly reported issue