您可以在 Python 类型注释中指定方差吗?
Can you specify variance in a Python type annotation?
你能找出下面代码中的错误吗? 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())}")
Python 发现错误,当然,有助于通知我们 'int' object has no attribute 'lower'
。太糟糕了,直到 运行 时间它才能告诉我们这一点。
据我所知,mypy 没有捕捉到这个错误,因为它允许 add_items
的 d
参数的参数是协变的。如果我们只从字典中阅读,那将是有道理的。如果我们只是阅读,那么我们希望参数是协变的。如果我们准备读取任何类型,那么我们应该能够读取字符串类型。当然,如果我们只是阅读,那么我们应该输入 typing.Mapping
.
既然我们在写,我们实际上希望参数是逆变。例如,对于某人传递 Dict[Any, Any]
是完全合理的,因为它完全能够存储字符串键和整数值。
如果我们正在阅读和写作,除了参数不变之外别无选择。
有没有办法指定我们需要什么样的方差?更好的是,mypy 是否足够复杂,可以合理地期望它通过静态分析来确定方差,并且应该将其作为错误归档?还是 Python 中类型检查的当前状态根本无法捕获此类编程错误?
你的分析不正确——这其实和方差无关,mypy中的Dict类型其实是不变的w.r.t。到它的价值。
相反,问题在于您已将 Dict 的值声明为 Any
类型,即动态类型。这实际上意味着您希望 mypy 基本上不对与您的 Dict 值相关的任何内容进行类型检查。由于您选择退出类型检查,它自然不会发现任何与类型相关的错误。
(这是通过神奇地将 Any
放置在类型格的顶部和底部来实现的。基本上,给定某种类型 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)
只有对accept_b
的调用成功,符合预期的方差。
回答你关于如何设置方差的问题 -- mypy 的设计使得数据结构的方差在定义时设置并且不能在调用时真正改变。
因此,由于 Dict 被定义为不变的,因此您不能真正将事后更改为协变或不变。
有关在定义时设置方差的更多详细信息,请参阅 mypy reference docs on generics。
正如您所指出的,您可以通过使用映射来声明您想要接受 Dict 的只读版本。通常情况下,您可能想要使用任何 PEP 484 数据结构的只读版本——例如Sequence 是 List 的只读版本。
据我所知,Dict 没有默认的只写版本。但是你可以通过使用 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)
要回答您隐含的问题 ("How do I get mypy to detect the type error here/properly type check my code?"),答案是 "simple"——只要不惜一切代价避免使用 Any
。每次这样做,都是在故意在类型系统中打开一个漏洞。
例如,声明字典的值可以是任何类型的更安全的方法是使用 Dict[str, object]
。现在,mypy 会将对 add_items
函数的调用标记为非类型安全。
或者,如果您知道您的值将是异构的,请考虑使用 TypedDict。
您甚至可以通过启用 Disable dynamic typing 系列命令行 flags/config 文件标志,使 mypy 禁止 Any 的某些用法。
也就是说,在实践中,完全禁止使用 Any 通常是不现实的。即使您可以在您的代码中满足这个理想,许多第 3 方库要么没有注释,要么没有完全注释,这意味着它们到处都使用 Any。因此,不幸的是,完全删除它们的使用往往最终需要大量额外的工作。
你能找出下面代码中的错误吗? 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())}")
Python 发现错误,当然,有助于通知我们 'int' object has no attribute 'lower'
。太糟糕了,直到 运行 时间它才能告诉我们这一点。
据我所知,mypy 没有捕捉到这个错误,因为它允许 add_items
的 d
参数的参数是协变的。如果我们只从字典中阅读,那将是有道理的。如果我们只是阅读,那么我们希望参数是协变的。如果我们准备读取任何类型,那么我们应该能够读取字符串类型。当然,如果我们只是阅读,那么我们应该输入 typing.Mapping
.
既然我们在写,我们实际上希望参数是逆变。例如,对于某人传递 Dict[Any, Any]
是完全合理的,因为它完全能够存储字符串键和整数值。
如果我们正在阅读和写作,除了参数不变之外别无选择。
有没有办法指定我们需要什么样的方差?更好的是,mypy 是否足够复杂,可以合理地期望它通过静态分析来确定方差,并且应该将其作为错误归档?还是 Python 中类型检查的当前状态根本无法捕获此类编程错误?
你的分析不正确——这其实和方差无关,mypy中的Dict类型其实是不变的w.r.t。到它的价值。
相反,问题在于您已将 Dict 的值声明为 Any
类型,即动态类型。这实际上意味着您希望 mypy 基本上不对与您的 Dict 值相关的任何内容进行类型检查。由于您选择退出类型检查,它自然不会发现任何与类型相关的错误。
(这是通过神奇地将 Any
放置在类型格的顶部和底部来实现的。基本上,给定某种类型 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)
只有对accept_b
的调用成功,符合预期的方差。
回答你关于如何设置方差的问题 -- mypy 的设计使得数据结构的方差在定义时设置并且不能在调用时真正改变。
因此,由于 Dict 被定义为不变的,因此您不能真正将事后更改为协变或不变。
有关在定义时设置方差的更多详细信息,请参阅 mypy reference docs on generics。
正如您所指出的,您可以通过使用映射来声明您想要接受 Dict 的只读版本。通常情况下,您可能想要使用任何 PEP 484 数据结构的只读版本——例如Sequence 是 List 的只读版本。
据我所知,Dict 没有默认的只写版本。但是你可以通过使用 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)
要回答您隐含的问题 ("How do I get mypy to detect the type error here/properly type check my code?"),答案是 "simple"——只要不惜一切代价避免使用 Any
。每次这样做,都是在故意在类型系统中打开一个漏洞。
例如,声明字典的值可以是任何类型的更安全的方法是使用 Dict[str, object]
。现在,mypy 会将对 add_items
函数的调用标记为非类型安全。
或者,如果您知道您的值将是异构的,请考虑使用 TypedDict。
您甚至可以通过启用 Disable dynamic typing 系列命令行 flags/config 文件标志,使 mypy 禁止 Any 的某些用法。
也就是说,在实践中,完全禁止使用 Any 通常是不现实的。即使您可以在您的代码中满足这个理想,许多第 3 方库要么没有注释,要么没有完全注释,这意味着它们到处都使用 Any。因此,不幸的是,完全删除它们的使用往往最终需要大量额外的工作。