Python类型提示和`*args`

18
假设我有以下这个函数:

Assume I have a function like this:

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


你的第一种方法是正确的,使用 Tuple[int, ..],而 *args: int 则总是错误的,因为 Python 会为 *args 创建一个包含多余位置参数值的元组。 - Dimitris Fasarakis Hilliard
@JimFasarakisHilliard 看起来 *args**kwargsPEP 0484 中被特殊处理,正如现在已经接受的答案所述。 - llf
2个回答

15
根据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)

0
你应该查看文档字符串。PyCharm允许你在文档字符串中定义参数,带或不带类型。如果你定义了类型,提示将考虑参数的类型。
def foo(*args):
    """
    General information about foo
    :param [int] args: info about args
    """

    for x in args:
        print(x)

很好,作为一个快速修复,它似乎有效。我仍然更喜欢基于类型提示和函数注释的解决方案,但如果没有其他办法,我会接受这个。 - gcali

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接