【发布时间】:2022-06-17 22:45:07
【问题描述】:
PEP612 将ParameterSpec 添加到typing 模块,允许您对由函数装饰器包装的函数进行类型检查(并在Concatenate 的帮助下对装饰器本身进行类型检查)。
在导致接受 PEP 的讨论之一中,引用了函数简单地将 *args、**kwargs 转发到其他函数的场景,但据我所知,除非您使用装饰器,否则仍然不支持这种情况因为 ParamSpec 只能在 Callable 类型已经在作用域内时使用。
例如,我不知道以下任何一个是否适合(如果有的话):
def plot_special(df: pd.DataFrame, p1: int, p2: int, *plot_args, **plot_kwargs) -> None:
# do something with p1, p2
df.plot(*plot_args, **plot_kwargs)
或
class A:
def f(self, x: int, y: int) -> int:
return x + y
class B:
def __init__(self) -> None:
self.a = A()
f = A.a # Does not work, self is not of type A
# Since B.f is not wrapping A.f, does not seem to be a way
# to contextualize a ParameterSpec
def f(self, *args, **kwargs) -> int:
self.a.f(*args, **kwargs)
或
class A:
def __int__(self, p1: int, p2: int) -> None:
self.p1 = p1
self.p2 = p2
def f(x: int, y: int) -> int:
return x + y
class MixinForA:
def __init__(self, p3: str, *args, **kwargs) -> None:
self.p3 = p3
super().__init__(*args, **kwargs)
除非 *args 和 **kwargs 是同质的,否则我们似乎仍然无法利用从其他函数调用的类型检查函数,而这些函数只希望传递 *args、**kwargs(而不是复制函数签名)。
【问题讨论】:
标签: python types mypy typechecking