python dect键和值在哪里取决于相同的通用类型
我想定义一个键,其键和值共享相同的通用类型,并且对其有一些约束。以下是这种情况的例子。但是,将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的钥匙和价值之间添加类型约束。
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]] = {}
I want to define a dict whose key and value are share the same generic type and has some constraint with it. The following is the example of such a situation. However, applying mypy
to the following code cause an error:
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)
How to fix this?
The reason why I need such a dict is that I want to add a type constraint between dict's key and value.
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]] = {}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我最终通过定义从
dict
继承的自定义dict来避免此问题。Mypy的结果是我预期的:
I finally circumvent this problem by defining custom dict that inherited from the
Dict
.mypy result is as I expected: