-
-
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
Safe cast (upcast) #5756
Comments
Remind us what "proper subtype" means and how it differs from "subtype"? |
FWIW, I believe it would be trivial to implement def safe_cast(form: TypeForm[T], value: T) -> T
return value |
I definitely agree. Currently it is not possible to implement a custom variant of The reason to have these functions is that they are not noops but also perform further analysis on the structure and values of the types (e.g. many of them are dicts but not static enought to use typed dicts and some others like |
It's mypy jargon. It's basically "standard subtype" with no special rules for Plain "subtype" recognizes |
Sometimes I want to give a hint to mypy about a type of an expression.
cast()
works here, but it's inherently unsafe. If I make a mistake, my program may crash at runtime. If we had a "safe cast" operation instead that would only allow casts that can't introduce runtime failures, mypy could catch some additional errors, and the use ofcast()
could be reduced a bit.Here's an example derived from an example in mypy of where it would be helpful:
In this case an alternative would be to improve type checking or type inference in mypy, but there will likely always be cases where mypy won't get thing right, and being able to perform a cast would be helpful.
Semantics of
safe_cast
:At runtime
safe_cast
just returns the second argument, similar tocast
.More generally, if we had
safe_cast
, we could plausibly use binder on initial assignment (#2008), sincesafe_cast
would be a simple workaround for cases where using binder is not desirable. Example where this would make a difference:Now if the revealed type was
int
, we could usesafe_cast
to get the original behavior without introducing type unsafety:Safe cast has these benefits over
cast()
:Related issues: #5750 (example where this could be helpful), #5687 (safer downcasts)
The text was updated successfully, but these errors were encountered: