我怎样才能注释f(*params)?

Bar*_*cki 3 python typing argument-unpacking python-3.x python-3.6

我无法弄清楚如何正确地注释这段代码:

from typing import Iterable

def f(*params: Iterable) -> str:
    return ":".join(params)
Run Code Online (Sandbox Code Playgroud)

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

error: Argument 1 to "join" of "str" has incompatible type Tuple[Iterable[Any], ...]; expected Iterable[str]
Run Code Online (Sandbox Code Playgroud)

......但我不明白为什么.

Zer*_*eus 6

当注释与*args-style参数列表组合时,注释指定了预期每个参数的类型.如PEP 484所述:

任意参数列表也可以是类型注释,以便定义:

def foo(*args: str, **kwds: int): ...
Run Code Online (Sandbox Code Playgroud)

是可接受的,这意味着,例如,以下所有代表使用有效类型的参数的函数调用:

foo('a', 'b', 'c')
foo(x=1, y=2)
foo('', z=0)
Run Code Online (Sandbox Code Playgroud)

在的函数的体foo,变量的类型args被推导出 Tuple[str, ...]与变量的类型kwdsDict[str, int].

在您的示例中,由于params预期是字符串元组,因此正确的注释是str:

def f(*params: str) -> str:
    return ":".join(params)
Run Code Online (Sandbox Code Playgroud)