How to properly type-hint a Python dict whose keys are Type[T] and values are generics of that type?

Viewed 206

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.

1 Answers

Consider declaring an EventRecord type that will represent the relation between the event type and the list of events.

from abc import ABC
from dataclasses import dataclass, field
from typing import Generic, TypeVar


class Event(ABC):
    pass


class MessageReceived(Event):
    pass


class MessageSent(Event):
    pass


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


@dataclass
class EventRecord(Generic[EventT]):
    event_type: type[EventT]
    events: list[EventT] = field(default_factory=list)


event_registry = {
    EventRecord(event_type=MessageSent),
    EventRecord(event_type=MessageReceived),
}
Related