gpt4 book ai didi

python - *args 和 **kwargs 的类型注释

转载 作者:IT老高 更新时间:2023-10-28 21:11:36 28 4
gpt4 key购买 nike

我正在尝试使用抽象基类来编写 Python 的类型注释来编写一些接口(interface)。有没有办法注释 *args**kwargs 的可能类型?

例如,如何表示函数的合理参数是一个 int 或两个 inttype(args) 给出 Tuple 所以我的猜测是将类型注释为 Union[Tuple[int, int], Tuple[int]] ,但这不起作用。

from typing import Union, Tuple

def foo(*args: Union[Tuple[int, int], Tuple[int]]):
try:
i, j = args
return i + j
except ValueError:
assert len(args) == 1
i = args[0]
return i

# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))

来自 mypy 的错误消息:

t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]")
t.py: note: At top level:
t.py:12: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:14: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 1 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"
t.py:15: error: Argument 2 to "foo" has incompatible type "int"; expected "Union[Tuple[int, int], Tuple[int]]"

mypy 不喜欢这个函数调用是有道理的,因为它希望调用本身有一个 tuple。解压后的加法也出现了我看不懂的打字错误。

如何注释 *args**kwargs 的合理类型?

最佳答案

对于可变位置参数 (*args) 和可变关键字参数 (**kw),您只需为 one 这样的论点。

来自 Arbitrary argument lists and default argument values section 类型提示 PEP:

Arbitrary argument lists can as well be type annotated, so that the definition:

def foo(*args: str, **kwds: int): ...

is acceptable and it means that, e.g., all of the following represent function calls with valid types of arguments:

foo('a', 'b', 'c')
foo(x=1, y=2)
foo('', z=0)

所以你想像这样指定你的方法:

def foo(*args: int):

但是,如果您的函数只能接受一个或两个整数值,则根本不应该使用 *args,而是使用一个显式位置参数和第二个关键字参数:

def foo(first: int, second: Optional[int] = None):

现在您的函数实际上仅限于一个或两个参数,并且如果指定,则两者都必须是整数。 *args always 表示 0 或更多,并且不能被类型提示限制到更具体的范围。

关于python - *args 和 **kwargs 的类型注释,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37031928/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com