How to handle Callable with covariant argument as class member variable. #858
Replies: 2 comments 2 replies
-
@dataclass
class Endpoint:
handler: Callable[[RT], None]
def assign_handler(self, h: Callable[[RT], None]) -> 'Endpoint':
self.handler = h
return self One note: @dataclass
class Endpoint:
handler: Callable[[Request], None]
def assign_handler(self, h: Callable[[Request], None]) -> 'Endpoint':
self.handler = h
return self And of course (Also, I would recommend to change the return type of the callable to Using a generic is the best solution, in my opinion. Using the following should work: WebappG(
[
EndpointG(handler1),
EndpointG(handler2),
]
) So should the following if you want to construct the list: endpoints: list[EndpointG[Any]] = [EndpointG(handler1)]
endpoints.extend([EndpointG(handler2)])
WebappG(endpoints) |
Beta Was this translation helpful? Give feedback.
-
Not a full answer, but I wanted to respond to this part:
ParamSpec is actually available for all Python >=3.5 through the In general this is true for all non-syntactic changes to typing: we backport them and typecheckers will support them regardless of Python version. |
Beta Was this translation helpful? Give feedback.
-
Imagine building a web app which has different handler for different endpoints
Here you can see the case 2 is throwing typing error but the same type doesn't throw typing error when passed as function argument (case 3).
I understand, we can solve this by introducing
Generic
but that add bit more complexity,To solve this typing error, I need to cast and merge list to
WebappG
. Is there any other better way to handle this use case?I hope this can be solved with
ParamSpec
but it's available only on Python 3.10. Is there any other better way to handle this use case?Beta Was this translation helpful? Give feedback.
All reactions