Is it possible to narrow between generic type[_T] and Callable[[Any], _T]? #11164
Unanswered
aakhavanQC
asked this question in
Q&A
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I have a library that looks something like this:
The basic idea is to strongly type functions that are actually run outside of python by validating the response. Currently, you can give it either the return type as an argument, or a class with a
validate_responseclass method that returns an instance of the class (convenient for validation with pydantic, for example). The problem with this approach is that it forces the validation function to return an instance of the same class it belongs to because it prevents you from easily being able to deeply validate lists/dicts.To address this, I want to change
return_typeto beCallable[[Any], _T]. This means it will take any function whose return type matches the class generic type. The downside, though, is you can no longer give it primitives like theRemoteFunction(int)example. So I triedtype[_T] | Callable[[Any], _T], but I can't figure out how to get the type checker to distinguish between something that's built-in vs something that's actually a function. I know I could hardcode the primitive types, but worry that it's risky in that I might miss something.Ultimately what I'm looking for is something like this:
which allows both
and
Interestingly, pyright seems to correctly gets that
responsein the example is anint, even though it'sAnyin the scope of the method (mypy throws an error there though:# Incompatible return value type (got "object", expected "_T"))Beta Was this translation helpful? Give feedback.
All reactions