如何正确地对键为 Type[T] 且值是该类型的泛型的 Python 字典进行类型提示?

问题描述 投票:0回答:1

我想要一个字典暗示,使得值包含与键相同类型的泛型:

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
不受约束,但我无法找到一种方法来实际正确地暗示这一点。

python python-typing mypy
1个回答
0
投票

考虑声明一个

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),
}
© www.soinside.com 2019 - 2024. All rights reserved.