我最近一直在深入研究 MyPy,并从他们的文档中看到了以下示例
from typing import TypeVar, SupportsAbs
T = TypeVar('T', bound=SupportsAbs[float])
def largest_in_absolute_value(*xs: T) -> T:
return max(xs, key=abs) # Okay, because T is a subtype of SupportsAbs[float].
这表明可以使用 mypy 使得传入的泛型必须支持 abs 函数才能通过静态类型检查器。
但我不清楚它究竟是如何工作的。例如,如果我可以指定一个类型必须支持的任何函数,或者该类型必须介于两者之间的范围,我会认为这是非常强大的。
我的问题如下:有没有办法使用绑定(bind)来支持任何随机函数需求?例如,该类型必须支持 len
功能? (我怀疑这是可能的)
特定变量类型的范围如何(即小于 10 个字符的字符串,或小于 100 的 int)? (我怀疑这是不太可能的)
最佳答案
核心规则是:绑定(bind)需要是某种合法的 PEP-484 类型。
通常,所有这一切都是让您指定 T 最终必须由边界或边界的某个子类“填充”。例如:
class Parent: pass
class Child(Parent): pass
T = TypeVar('T', bound=Parent)
def foo(x: T) -> T: return x
# Legal; revealed type is 'Parent'
reveal_type(foo(Parent()))
# Legal; revealed type is 'Child'
reveal_type(foo(Child()))
# Illegal, since ints are not subtypes of Parent
foo(3)
通过将绑定(bind)设置为 Protocol,您可以做一些更有趣的事情.
基本上,假设您有这样一个程序:
class SupportsFoo:
def foo(self, x: int) -> str: ...
class Blah:
def foo(self, x: int) -> str: ...
# The two types are not related, so this fails with a
# 'Incompatible types in assignment' error -- the RHS needs
# to be a subtype of the declared type of the LHS.
x: SupportsFoo = Blah()
这两个类被 mypy 视为完全不相关:它们可能碰巧共享一个具有相同签名的函数 foo
,但 Blah
不继承自SupportsFoo
或相反,因此它们的相似性被视为巧合,因此被丢弃。
我们可以通过将 SupportsFoo
变成一个协议(protocol)来改变它:
# If you're using Python 3.7 or below, pip-install typing_extensions
# and import Protocol from there
from typing import Protocol
class SupportsFoo(Protocol):
def foo(self, x: int) -> str: ...
class Blah:
def foo(self, x: int) -> str: ...
# This succeeds!
x: SupportsFoo = Blah()
现在,这成功了! Mypy 理解 Blah
具有与 SupportsFoo
完全相同的签名的方法,因此将其视为前者的子类型。
这正是 SupportsAbs
发生的情况——您可以检查 definition of that type for yourself在 Typeshed 上,标准库的类型提示存储库。 (Typeshed 的副本被烘焙到每个 mypy 版本中):
@runtime_checkable
class SupportsAbs(Protocol[_T_co]):
@abstractmethod
def __abs__(self) -> _T_co: ...
是的,正如您所要求的,您还可以创建一个协议(protocol)来坚持输入类型使用 typing.Sized
实现 __len__
,其定义如下:
@runtime_checkable
class Sized(Protocol, metaclass=ABCMeta):
@abstractmethod
def __len__(self) -> int: ...
是的,您的直觉是没有一种干净的方法来创建断言诸如“此字符串必须等于或少于 10 个字符”或“这必须是一个小于 100 的 int”之类的类型。
我们可以种通过使用称为Literal types的不相关机制来支持它。通过这样做:
# As before, import from typing_extensions for Python 3.7 or less
from typing import Literal
BetweenZeroAndOneHundred = Literal[
0, 1, 2, 3, 4, 5,
# ...snip...
96, 97, 98, 99, 100,
]
但这很老套,而且实际上值(value)非常有限。
更好的解决方案是通常只在运行时进行自定义检查并使用 NewType :
from typing import NewType
LessThanOneHundred = NewType('LessThanOneHundred', int)
def to_less_than_one_hundred(value: int) -> LessThanOneHundred:
assert value < 100
return LessThanOneHundred(value)
这不是一个完美的解决方案,因为它要求您在运行时进行检查/要求您确保在完成运行时检查后每次“实例化”您的 NewType,但它是实际上以类型检查器可以理解的形式对任意运行时检查的结果进行编码的可用方法。
关于python - 将任意函数与 MyPy 的 TypeVar 绑定(bind)属性一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57041313/