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]] = {}
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