python dect键和值在哪里取决于相同的通用类型

发布于 2025-02-10 02:16:22 字数 692 浏览 1 评论 0原文

我想定义一个键,其键和值共享相同的通用类型,并且对其有一些约束。以下是这种情况的例子。但是,将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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

罪歌 2025-02-17 02:16:22

我最终通过定义从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

Mypy的结果是我预期的:

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)

I finally circumvent this problem by defining custom dict that inherited from the 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

mypy result is as I expected:

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文