-
-
Notifications
You must be signed in to change notification settings - Fork 2.9k
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
disjoint unions in mypy? #6863
Comments
Aren't you essentially trading off putinig lots of As for using |
But why this def output(message: Union[TextMessage, ImageMessage]) -> None:
if message.type == TEXT:
print(message.text) is better than this def output(message: Union[TextMessage, ImageMessage]) -> None:
if isinstance(message, TextMessage):
print(message.text) ? Anyway, I propose to close this since this is essentially the same as "Type narrowing with equality and inequality checks" item from #5935 as @ethanhs mentioned. |
Agreed! Interestingly, TypeScript does offer this feature (discriminating unions), but @mneira10 pointed out that they're more important in TS given that TS doesn't have a clean way of doing |
Besides, the original example works already if using Final and literal types:
|
I am trying to customize a function that takes an object of a union type and accesses different attributes depending on the type. The type of the object is specified by a
type
attribute.Mypy does not like this, saying:
And I understand it. I am trying to guess one attribute based on the value of another one. This is poor engineering.
However, the same thing works in other languages, for example, in JS Flow:
Live Flow link: here
So the question is, is there a way to make mypy understand my conditions? Maybe using
Literal
types? I tried to figure this out but the docs are a bit confusing.P.S. I can always do
if isinstance(message, TextMessage)
and this will satisfy mypy, but putting lots ofisinstance()
in my code seems even more hacky.The text was updated successfully, but these errors were encountered: