我想要定义一个dict,它的键和值共享相同的泛型类型,并且对它有一些约束。以下是这种情况的例子。但是,将
mypy
应用于以下代码会导致错误:
tmp.py:8: error: Type variable "tmp.AT" is unbound
tmp.py:8: note: (Hint: Use "Generic[AT]" or "Protocol[AT]" base class to bind "AT" inside a class)
tmp.py:8: note: (Hint: Use "AT" in function signature to bind "AT" inside a function)
Found 1 error in 1 file (checked 1 source file)
怎么解决这个问题?我需要这样一个dict的原因是我想在dict的键和值之间添加一个类型约束。
tmp.py:
from typing import Dict, Generic, TypeVar, Type, List
class A: pass
class B(A): pass
class C(A): pass
AT = TypeVar("AT", bound=A)
d: Dict[Type[AT], List[AT]] = {}
发布于 2022-06-26 01:25:26
我最终通过定义从
Dict
继承的自定义dict来解决这个问题。
from typing import Dict, TypeVar, Type, List
from dataclasses import dataclass
AT = TypeVar("AT")
class ConstrainedDict(Dict):
def __getitem__(self, k: Type[AT]) -> List[AT]:
return super().__getitem__(k)
class Foo: pass