[Python] How to properly type-hint a Python dict whose keys are Type[T] and values are...

Discussão em 'Python' iniciado por Stack, Fevereiro 8, 2025.

  1. Stack

    Stack Membro Participativo

    I'd like to have a dict hinted such that the values contain generics of a type that's the same as the key:

    from abc import ABC
    from typing import Dict, List, Type, TypeVar

    class Event(ABC):
    pass

    class MessageReceived(Event):
    pass

    class MessageSent(Event):
    pass

    EventT = TypeVar("EventT", bound=Event)

    events: Dict[Type[EventT], List[EventT]] = {}



    mypy returns an error along the lines of:

    Type variable "EventT" is unbound [valid-type]


    I understand why EventT is unbound, but I cannot work out a way to actually hint this properly.

    Continue reading...

Compartilhe esta Página