-
-
Notifications
You must be signed in to change notification settings - Fork 3k
Allow PEP 604 type aliases to be used in runtime context. #11650
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
Conversation
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.
Thank you for your work! 🎉
I have left several questions 🙂
|
||
class F(metaclass=Meta): pass | ||
|
||
reveal_type(F | F) # N: Revealed type is "types.UnionType" |
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.
I haven't personally used this trick yet, so I am thinking 🤔
Should not this be just F
? Or do we want this special treatment of types.UnionType
?
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.
I think there is confusion over Union
and UnionType
here (and imo, it is confusing and that's because unions are treated so specially). UnionType
is the runtime type of a Union
object:
X = str | int
print(type(X)) # <class 'types.UnionType'>
So, the type of X is always UnionType (it's worth noting that in previous version of mypy this was just builtins.object
).
This is perhaps easier to grasp given:
class A: ...
reveal_type(A | A) # types.UnionType
a: A | A
reveal_type(a) # Union[test2.A, test2.A]
Now, the second case not reducing is almost certainly a bug, but I think that is unrelated to this specific issue (it's also present in master) since it doesn't matter if its a TypeAlias
or not (just if it was a PEP 604 union or not).
It's been a while now, but this PR would still be useful. In the meantime I've worked around this using cast: class A: ...
class B: ...
C = A | B
isinstance(object(), cast(UnionType, C)) |
I think these all work on master with sufficiently new Python |
I ramble about this here #11648 😄
This only solves the main issue that I had with #11648 (that a metaclass
__or__
return type was lost in mypy when giving it a name).This does not address the issue of union type aliases not being use-able with
isinstance
:But it does get rid of the second error regarding argument 2 not being compatible and correctly reveals C as
types.UnionType
.