P D*_*ddy 6 python typing covariance mypy
你能发现下面代码中的错误吗?米皮不能。
from typing import Dict, Any
def add_items(d: Dict[str, Any]) -> None:
d['foo'] = 5
d: Dict[str, str] = {}
add_items(d)
for key, value in d.items():
print(f"{repr(key)}: {repr(value.lower())}")
Run Code Online (Sandbox Code Playgroud)
当然,Python 发现了错误,这有助于通知我们'int' object has no attribute 'lower'. 太糟糕了,直到运行时它才能告诉我们这一点。
据我所知, mypy 没有捕获此错误,因为它允许 参数的参数d是add_items协变的。如果我们只阅读字典,那就有意义了。如果我们只是读取,那么我们会希望参数是协变的。如果我们准备读取任何类型,那么我们应该能够读取字符串类型。当然,如果我们只是阅读,那么我们应该将其输入为typing.Mapping.
由于我们正在编写,所以我们实际上希望参数是逆变的。例如,某人传入 a 是完全有意义的Dict[Any, Any],因为它完全能够存储字符串键和整数值。
如果我们要进行读写,就别无选择,只能让参数保持不变。
有没有办法指定我们需要什么样的方差?更好的是, mypy 是否足够复杂,以至于期望它通过静态分析确定方差应该是合理的,并且这应该作为错误归档?或者 Python 中类型检查的当前状态根本无法捕获这种编程错误?
您的分析是不正确的——这实际上与方差无关,并且 mypy 中的 Dict 类型实际上对其值而言是不变的。
相反,问题在于您已将 Dict 的值声明为 type Any,即动态类型。这实际上意味着您希望 mypy 基本上不对与您的 Dict 值相关的任何内容进行类型检查。由于您已经选择退出类型检查,它自然不会发现任何与类型相关的错误。
(这是通过神奇地放置Any在类型网格的顶部和底部来完成的。基本上,给定某种 type T,情况Any总是 T 的子类型,并且T 始终是 的子类型Any。Mypy 会自动选择任何关系结果没有错误。)
通过运行以下程序,您可以看到 Dict 对于您自己来说是不变的:
from typing import Dict
class A: pass
class B(A): pass
class C(B): pass
def accepts_a(x: Dict[str, A]) -> None: pass
def accepts_b(x: Dict[str, B]) -> None: pass
def accepts_c(x: Dict[str, C]) -> None: pass
my_dict: Dict[str, B] = {"foo": B()}
# error: Argument 1 to "accepts_a" has incompatible type "Dict[str, B]"; expected "Dict[str, A]"
# note: "Dict" is invariant -- see http://mypy.readthedocs.io/en/latest/common_issues.html#variance
# note: Consider using "Mapping" instead, which is covariant in the value type
accepts_a(my_dict)
# Type checks! No error.
accepts_b(my_dict)
# error: Argument 1 to "accepts_c" has incompatible type "Dict[str, B]"; expected "Dict[str, C]"
accepts_c(my_dict)
Run Code Online (Sandbox Code Playgroud)
只有调用accept_b成功,这与预期的方差一致。
为了回答有关如何设置方差的问题 - mypy 的设计使得数据结构的方差在定义时设置,并且不能在调用时真正更改。
因此,由于 Dict 被定义为不变的,因此您无法事后真正将其更改为协变或不变。
有关在定义时设置方差的更多详细信息,请参阅有关泛型的 mypy 参考文档。
正如您所指出的,您可以使用映射声明您想要接受字典的只读版本。通常情况下,您可能想要使用的任何 PEP 484 数据结构都有一个只读版本 - 例如,序列是列表的只读版本。
据我所知,Dict 没有默认的只写版本。但是你可以通过使用protocols自己将它们组合在一起,protocols是一种有望很快成为标准化的结构性输入方法,而不是名义上的输入方法:
from typing import Dict, TypeVar, Generic
from typing_extensions import Protocol
K = TypeVar('K', contravariant=True)
V = TypeVar('V', contravariant=True)
# Mypy requires the key to also be contravariant. I suspect this is because
# it cannot actually verify all types that satisfy the WriteOnlyDict
# protocol will use the key in an invariant way.
class WriteOnlyDict(Protocol, Generic[K, V]):
def __setitem__(self, key: K, value: V) -> None: ...
class A: pass
class B(A): pass
class C(B): pass
# All three functions accept only objects that implement the
# __setitem__ method with the signature described in the protocol.
#
# You can also use only this method inside of the function bodies,
# enforcing the write-only nature.
def accepts_a(x: WriteOnlyDict[str, A]) -> None: pass
def accepts_b(x: WriteOnlyDict[str, B]) -> None: pass
def accepts_c(x: WriteOnlyDict[str, C]) -> None: pass
my_dict: WriteOnlyDict[str, B] = {"foo": B()}
# error: Argument 1 to "accepts_a" has incompatible type "WriteOnlyDict[str, B]"; expected "WriteOnlyDict[str, A]"
accepts_a(my_dict)
# Both type-checks
accepts_b(my_dict)
accepts_c(my_dict)
Run Code Online (Sandbox Code Playgroud)
为了回答你隐含的问题(“我如何让 mypy 检测这里的类型错误/正确地检查我的代码?”),答案很“简单”——不惜Any一切代价避免使用。每次这样做,你都是在故意在类型系统中打开一个漏洞。
例如,声明字典的值可以是任何内容的更类型安全的方法是使用Dict[str, object]. 现在,mypy 会将函数调用标记add_items为非类型安全。
或者,如果您知道您的值将是异构的,请考虑使用TypedDict 。
您甚至可以通过启用命令行标志/配置文件标志的禁用动态类型系列来使 mypy 禁止 Any 的某些使用。
也就是说,在实践中,完全禁止使用 Any 通常是不现实的。即使您可以在代码中满足这一理想要求,许多第 3 方库要么未注释,要么未完全注释,这意味着它们到处使用 Any。因此,不幸的是,完全消除它们的使用往往最终需要大量的额外工作。
| 归档时间: |
|
| 查看次数: |
6003 次 |
| 最近记录: |