Python 输入提示和 `*args`

Python type hints and `*args`

假设我有这样一个函数:

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 中有效地使用类型提示,并且 none 我想到的解决方案似乎有助于 PyCharm 理解 x 应该是 int.

您应该看看文档字符串。 PyCharm 允许你在文档字符串中定义你的参数,有或没有类型。如果您定义类型,提示将考虑参数的类型。

def foo(*args):
    """
    General information about foo
    :param [int] args: info about args
    """

    for x in args:
        print(x)

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