[Python] Type hint dict keys and values with matching generic type

Discussão em 'Python' iniciado por Stack, Maio 16, 2025.

  1. Stack

    Stack Membro Participativo

    I have a class that behaves like a wrapper around some object. The object will always be a subclass of some parent class, but otherwise it can be anything (to simplify, I assume this parent class is object in my example). Therefore, I made the Wrapper class generic.

    I now want to have a dict that maps some objects classes to their corresponding wrapper class. The wrapper will always correspond, no issubclass check (or similar) needed from a runtime perspective. As far as I can tell, it is not even possible, because I use some generic method to perform the mapping.

    I would like to reflect this in my type hints, i.e. the type checker should only allow key-value-pairs with types type[SomeObject], type[Wrapper[SomeObject]].

    This is mostly relevant when accessing the dict, if I access the value for the key SomeObject, then the result should be type narrowed to Wrapper[SomeObject].

    TypeVars do not work for me though (and I assume they are not intended for this use case):

    wrapper_mapping: dict[type[T], type[Wrapper[T]]] # Does not work


    Is it even possible with the current type hint system? How can I make the type checker happy, without using ignore comments?

    class Wrapper[T]:
    def __init__(self, thing: T):
    self.thing: T = thing

    class StringWrapper(Wrapper[str]):
    def __init__(self, thing: str):
    thing += "!!!"
    super().__init__(thing)

    wrapper_mapping = {str: StringWrapper, int: Wrapper[int]}

    def wrap[T](thing: T) -> Wrapper[T]:
    # A lot of type checker warnings, but works at runtime
    return wrapper_mapping[type(thing)](thing)

    print(wrap("hello").thing) # hello!!!
    print(wrap(2).thing) # 2


    mypy-playground basedpyright-playground

    Continue reading...

Compartilhe esta Página