我想要定义一个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
class Bar: pass
d: ConstrainedDict
a: List[Foo] = d[Foo] # expected to pass
b: List[Foo] = d[Bar] # expected to cause error
我所期望的结果是:
tmp.py:15: error: Invalid index type "Type[Bar]" for "ConstrainedDict"; expected type "Type[Foo]"
Found 1 error in 1 file (checked 1 source file)
https://stackoverflow.com/questions/72743074
复制相似问题