-
-
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
Support some form of limited cast #941
Comments
This is actually how casts work in Java, for example (at least with classes). Due to multiple inheritance, two Python classes could theoretically almost always intersect. This might still be a reasonable thing to have and could catch some additional type errors, but this is not a high-priority feature as long as |
I guess instead of "nonzero intersection" it would be "iff one of the types is a subtype of the other" which rules out the I feel like this would cover the majority of cases where casting is actually useful (and in fact I would term the actual PEP484 cast as being a coerce, not a cast). |
I think this is similar to the downcast() idea. |
Just to add some thoughts about similar usecases, a case I often find is something like a function that returns
This would be better if we could say "this is not X". e.g. Something like Alternatively, it could work as an include, saying what the type is, but also requiring the original type to be a superset of this. The |
I'm going to close in favour of #5756, which (if I understand correctly) is basically the same proposal, but has had much more discussion in the years since. Feel free to reopen if I misunderstood! |
Support a softer, more limited alternative to
cast
.This isn't in PEP 484, so it can't be the behavior of
cast
.One of the common reasons of cast is that we "believe" for some reason that despite the original type of the variable being class A, it is in fact class B.
Currently, if we have
the two types would have no intersection, so if
A
was a correct type, it is neverB
. On the other hand, if we haveThen
B
andA
have nonzero intersection and thus such a cast is at least plausible. It would be nice to have a softcast that allows the latter case but not the former.Plausible reason to not support this:
if isinstance(...)
is arguably a better approach. I'm on the fence about it, but it seems like a nice thing to have.The text was updated successfully, but these errors were encountered: