gpt4 book ai didi

Python 类型提示和 `*args`

转载 作者:太空狗 更新时间:2023-10-29 21:54:47 27 4
gpt4 key购买 nike

假设我有这样一个函数:

def foo(*args):
for x in args:
print(x)

假设我想说 args 的所有元素都是 int;自 PEP 0484 起,正确的表达方式是什么? ?我应该做类似的事情吗

from typing import Tuple


def foo(*args: Tuple[int, ...]) -> None:
for x in args:
print(x)

或者类似的东西

def foo(*args: int) -> None:
for x in args:
print(x)

还是完全不同的东西?

特别是,我试图在 PyCharm 中有效地使用类型提示,而我想到的所有解决方案似乎都无法帮助 PyCharm 理解 x 应该是 int.

最佳答案

根据 PEP-484 :

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)

In the body of function foo, the type of variable args is deduced as Tuple[str, ...] and the type of variable kwds is Dict[str, int].

从您的示例中注释 foo 函数的正确方法是:

def foo(*args: int) -> None:
for x in args:
print(x)

在 Python 2 中:

def foo(*args):
# type: (*int) -> None
for x in args:
print(x)

关于Python 类型提示和 `*args`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940323/

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