How to accurately use a function as a type? #1935
-
I'm really not sure what to search for, so I apologise if this has already been covered. We're trying to type check our tests with a function that is passed through a fixture. The problem is how to annotate the fixture to get the function type correctly. Here's a snippet of the code we're currently using: from propcache.api import under_cached_property
class APIProtocol(Protocol):
under_cached_property: type[under_cached_property]
def test_under_cached_property(propcache_module: APIProtocol) -> None:
class A:
def __init__(self) -> None:
self._cache: dict[str, int] = {}
@propcache_module.under_cached_property
def prop(self) -> int:
return 1 The problem is that there is a Generic in the function signature. So, this code actually infers that generic as Any (i.e. If we were to add a TypeVar and use Is there any way to declare the type as exactly the function, so any generics are handled the same way as using the function directly? Failing that, any tips on how to workaround this? I really want type checking on these tests as we've already missed serious type checking failures due to this issue. The reason for the fixture is that the tests are executed twice with Python and Cython implementations of the modules. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
I believe what you want is this: class APIProtocol(Protocol):
def under_cached_property(self, method: Callable[[Any], T]) -> under_cached_property[T]: ... You want |
Beta Was this translation helpful? Give feedback.
I believe what you want is this:
You want
under_cached_property
to be a generic method, rather than the entire protocol being generic.