[英]How to properly type-hint a Python dict whose keys are Type[T] and values are generics of that type?
我想要一个 dict 提示,以便值包含与键相同的类型的 generics :
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),
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.