Python Forum
Python generics: How to infer generic type from class attribute?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Python generics: How to infer generic type from class attribute?
#1
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:

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: Any
However, 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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Initiating an attribute in a class __init__: question billykid999 8 1,355 May-02-2023, 09:09 PM
Last Post: billykid999
  Use a class type in it MathisDELAGE 2 917 Jan-29-2023, 11:37 AM
Last Post: MathisDELAGE
  search a list or tuple for a specific type ot class Skaperen 8 1,946 Jul-22-2022, 10:29 PM
Last Post: Skaperen
  class, attribute and method Frankduc 9 2,482 Feb-27-2022, 09:07 PM
Last Post: deanhystad
  AttributeError class object has no attribute list object scttfnch 5 3,465 Feb-24-2021, 10:03 PM
Last Post: scttfnch
  "can't set attribute" on class DreamingInsanity 2 10,884 Aug-22-2020, 07:57 PM
Last Post: DreamingInsanity
  AttributeError: type object 'FunctionNode' has no attribute '_TestValidateFuncLabel__ binhduonggttn 0 2,250 Feb-19-2020, 11:29 AM
Last Post: binhduonggttn
  Type hinting - return type based on parameter micseydel 2 2,499 Jan-14-2020, 01:20 AM
Last Post: micseydel
  Object and type class Uchikago 2 2,243 Jul-28-2019, 10:35 AM
Last Post: DeaD_EyE
  Class has no attribute <obj-name> arunprasanth 2 4,563 Mar-18-2019, 02:08 PM
Last Post: arunprasanth

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020