如何注释 f(*params)?

How can I annotate f(*params)?

我不知道如何正确注释这段代码:

from typing import Iterable

def f(*params: Iterable) -> str:
    return ":".join(params)

我知道 Iterable 是不正确的,因为 mypy 告诉我:

error: Argument 1 to "join" of "str" has incompatible type Tuple[Iterable[Any], ...]; expected Iterable[str]

……但是我不明白为什么。

当注解与 *args 风格的参数列表结合使用时,注解指定了每个预期参数的类型。如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].

在你的例子中,由于 params 应该是一个字符串元组,正确的注释是 str:

def f(*params: str) -> str:
    return ":".join(params)