我想要一个字典暗示,使得值包含与键相同类型的泛型:
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 返回如下错误:
Type variable "EventT" is unbound [valid-type]
我理解为什么
EventT
不受约束,但我无法找到一种方法来实际正确地暗示这一点。
考虑声明一个
EventRecord
类型来表示事件类型和事件列表之间的关系。
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),
}