Repository navigation
Optinal in Callable with self
#2285
Replies: 2 comments
|
The protocol should look somewhat like this (untested): class AuthWrapper[**P, R]:
def __call__(self, client: ApiClient, client_id: str | None = None, /, *args: P.args, **kwargs: P.kwargs) -> R: ...(The "self" here refers to the callable itself, not the client object.) |
|
I think the tricky part here is that Since from typing import Protocol, TypeVar, ParamSpec
P = ParamSpec("P")
R = TypeVar("R")
class WrappedMethod(Protocol[P, R]):
def __call__(
self,
client_id: str | None = None,
*args: P.args,
**kwargs: P.kwargs,
) -> R: ...The exact typing depends on whether the decorated function is a bound method or an unbound method, since The important distinction is that |
Uh oh!
There was an error while loading. Please reload this page.
For a an complex API client I have build an decorator which injects a http session into the method inside a class.
The function inside the decorator looks ruffly like this:
The typing of the decorator is slightly wrong since the
wrapperfunction defines a default value ofNone. But I haven't found a way to tell my type checker that.The mypy docs say that Protocol classes are the correct way to type this, but I wasn't able with the
selfparameter. Can someone point me into the correct direction?All reactions