-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Fix isinstance with type aliases to PEP 604 unions #17371
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. ✅ |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
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