Apr-25-2021, 09:31 AM
Let's say I have a number of requests types each of which correspond to exactly one reponse type. Each request is represented as a subclasse of the Request class.
I also have a function which takes a Request as an argument and returns the response (of the corresponding type). I would like to get a static type hint about the concrete response type depending on which Request subclass was passed.
I tried doing it like so:
P.S. I'm referring to the type hints which my IDE provides (PyCharm).
UPD: I also figured that I could add a generic parameter to the definiton of the subclasses:
I also have a function which takes a Request as an argument and returns the response (of the corresponding type). I would like to get a static type hint about the concrete response type depending on which Request subclass was passed.
I tried doing it like so:
from typing import TypeVar, Generic, Type
ResponseType = TypeVar("ResponseType")
class Request(Generic[ResponseType]):
response_type: Type[ResponseType]
class IsProcessedStartedRequest(Request):
response_type = bool
class GetIdRequest(Request):
response_type = str
def send_request(request: Request[ResponseType]) -> ResponseType:
...
request = GetIdRequest() # inferred type: GetIdRequest
response = send_request(request) # inferred type: AnyHowever, the inferred type of the response variable is not 'str' as I would expect, but 'Any'.P.S. I'm referring to the type hints which my IDE provides (PyCharm).
UPD: I also figured that I could add a generic parameter to the definiton of the subclasses:
class GetIdRequest(Request[str]):but this still doesn't solve the issue.
