Home > Mobile >  Use a generic parameter as a Literal
Use a generic parameter as a Literal

Time:01-20

I'm trying to play around with creating an api and I have different functions that handle requests to the api.

Some of the methods return a 204 rersponse and I want to typehint the return type of the method to a response with the statuscode 201.

def something() -> Response[204]:
    ...

I thought of creating a subclass of the real Response class that will be returned, and then just set the status_code variable to the Literal T.

class Response(Generic[T], TheOtherResponseClass):
    status_code: Literal[T]

My question is now how do I get the generic parameter T work with the Literal object from the typing module, if possible?

CodePudding user response:

This is the closest I can think of:

from typing import Generic, Literal, TypeVar

class TheOtherResponseClass:
    status_code: int

T = TypeVar('T', bound=int)

class Response(Generic[T], TheOtherResponseClass):
    status_code: T

class Response204(Response[Literal[204]]):
    status_code: Literal[204] = 204

reveal_type(Response204.status_code)

Running mypy on that file will give you

note: Revealed type is "Literal[204]"
  •  Tags:  
  • Related