-
-
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
Supporting runtime checked cast functions for generic types #15682
Comments
If you're looking at that comment of mine #9773 (comment) and are are actually desperate, you can combine it with an |
Interesting, yes that might actually work. However you do still end up end up with |
Is there anything actionable for mypy to implement, or are you requesting some addition to the Python type system? If it's the latter, then the python/typing discussion forum would be a better place for the request. |
Agreed, there's nothing actionable for mypy here |
I wanted to keep the issue description broad to avoid an X-Y problem. There are several linked mypy-specific issues which may help towards my formulated goal. I also thought that other developers have the same issue and this could make it worthwhile to eventually include a idiomatic solution in the mypy documentation along the type system reference. But I don't mind closing this for now. Developers with the same issue can still contribute here and if a idiomatic solution becomes nearer we can go there... |
@tilsche did you end up opening a discussion on this somewhere else? I'm also interested in a better way to accomplish this. |
Feature
Provide or allow to implement a function that both casts a value to a given type and does a runtime check, raising a
TypeError
if it does not match.Pitch
Most commonly, type narrowing / type guards are used to combine runtime and static type checking:
However, this does not work in many situations when used within expressions here conciseness is wanted. Consider:
We would have to write it as:
Now I often find myself implementing
Unfortunately this does not support anything but basic types, in particular no unions. And I cannot seem to get support for unions.
This seems to be related to the issues #15662, #9003, and #9773.
There is a proposed workaround with a type annotation class: #9773 (comment). However, I cannot get the actual generic type at runtime unless explicit subclasses are created:
At this time I am desperate and looking for solutions and viable workarounds here. While there are a number of related issues that when resolved would allow implementing this, I could not find an issue that specifically focuses on this use-case.
The text was updated successfully, but these errors were encountered: