hoo*_*one 5 python typing mypy
我正在写一个zip_with带有以下签名的函数:
_A = TypeVar("_A")
_B = TypeVar("_B")
_C = TypeVar("_C")
def zip_with(zipper: Callable[[_A, _B], _C], a_vals: Iterable[_A], b_vals: Iterable[_B]) -> Generator[_C, None, None]: ...
Run Code Online (Sandbox Code Playgroud)
就像zip,但是允许您与任意函数进行聚合。对于zip_with仅允许2个参数的实现,此方法效果很好。
是否支持为可变数量的参数添加类型提示?具体来说,我想要一个任意的泛型类型列表,并且希望类型检查器能够将参数的类型与的参数进行匹配zipper。没有特定类型的方法如下:
def zip_with(zipper: Callable[..., _C], *vals: Iterable) -> Generator[_C, None, None]: ...
Run Code Online (Sandbox Code Playgroud)
换句话说,我希望类型检查器能够将的类型*vals与的输入参数进行匹配zipper。
不幸的是,没有一种干净的方式来表达这种类型签名。为此,我们需要一个称为可变泛型的功能。尽管人们普遍有兴趣将这一概念添加到 PEP 484 中,但这可能不会在短期内发生。
特别是对于 mypy 核心团队,我粗略估计此功能的工作可能会在今年晚些时候开始,但最早可能要到 2020 年初到中期才能投入使用。(这是基于与团队中各个成员的一些面对面对话。)
当前的解决方法是滥用重载,如下所示:
from typing import TypeVar, overload, Callable, Iterable, Any, Generator
_T1 = TypeVar("_T1")
_T2 = TypeVar("_T2")
_T3 = TypeVar("_T3")
_T4 = TypeVar("_T4")
_T5 = TypeVar("_T5")
_TRet = TypeVar("_TRet")
@overload
def zip_with(zipper: Callable[[_T1, _T2], _TRet],
__vals1: Iterable[_T1],
__vals2: Iterable[_T2],
) -> Generator[_TRet, None, None]: ...
@overload
def zip_with(zipper: Callable[[_T1, _T2, _T3], _TRet],
__vals1: Iterable[_T1],
__vals2: Iterable[_T2],
__vals3: Iterable[_T3],
) -> Generator[_TRet, None, None]: ...
@overload
def zip_with(zipper: Callable[[_T1, _T2, _T3, _T4], _TRet],
__vals1: Iterable[_T1],
__vals2: Iterable[_T2],
__vals3: Iterable[_T3],
__vals4: Iterable[_T4],
) -> Generator[_TRet, None, None]: ...
@overload
def zip_with(zipper: Callable[[_T1, _T2, _T3, _T4, _T5], _TRet],
__vals1: Iterable[_T1],
__vals2: Iterable[_T2],
__vals3: Iterable[_T3],
__vals4: Iterable[_T4],
__vals5: Iterable[_T5],
) -> Generator[_TRet, None, None]: ...
# One final fallback overload if we want to handle callables with more than
# 5 args more gracefully. (We can omit this if we want to bias towards
# full precision at the cost of usability.)
@overload
def zip_with(zipper: Callable[..., _TRet],
*__vals: Iterable[Any],
) -> Generator[_TRet, None, None]: ...
def zip_with(zipper: Callable[..., _TRet],
*__vals: Iterable[Any],
) -> Generator[_TRet, None, None]:
pass
Run Code Online (Sandbox Code Playgroud)
这种方法显然相当不优雅——编写起来很笨拙,并且只对接受最多 5 个参数的可调用对象执行精确的类型检查。
但在实践中,这通常就足够了。实际上,大多数可调用函数都不会太长,如果需要,我们总是可以添加更多重载来处理更多特殊情况。
事实上,这种技术实际上是用来定义类型的zip:https://github.com/python/typeshed/blob/master/stdlib/2and3/builtins.pyi#L1403
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |