Repository navigation
Is it possible to narrow between generic type[_T] and Callable[[Any], _T]? #11164
Replies: 1 comment
|
You can normalize the argument into a validator once, in from collections.abc import Callable
from typing import Any, Generic, TypeVar, cast
T = TypeVar("T")
class RemoteFunction(Generic[T]):
def __init__(self, return_type: type[T] | Callable[[Any], T]):
if isinstance(return_type, type):
expected_type = cast(type[T], return_type)
def validate(response: Any) -> T:
if not isinstance(response, expected_type):
raise TypeError(f"Expected {expected_type.__name__}")
return response
self._validator: Callable[[Any], T] = validate
else:
self._validator = return_type
def validate(self, response: Any) -> T:
return self._validator(response)
integer = RemoteFunction(int)
value: int = integer.validate(42)
def parse_names(response: Any) -> list[str]:
if not isinstance(response, list):
raise TypeError("Expected a list")
items = cast(list[Any], response)
if not all(isinstance(item, str) for item in items):
raise TypeError("Expected string items")
return cast(list[str], items)
names = RemoteFunction(parse_names)
result: list[str] = names.validate(["Ada", "Grace"])The first cast records the constructor contract: the class supplied for this I checked this with Pyright 1.1.414 in strict mode and Python 3.12.14: both forms type-check, and the runtime checks reject a string supplied to the integer validator and a list containing a non-string supplied to |
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"))All reactions