简体   繁体   中英

Python Type Hinting: type hint a function with *args

Let's say we want to type hint a function that takes in a positional argument and an arbitrary number of more arguments, eg

def foo(a: int, *args: Any) -> None:
    for arg in args:
        print(a, isinstance(arg, int))

and we have another function that takes in foo , so we want to know how to type hint foo as itself. Is it correct to write it as Callable[[int, Any], None] ? I'm confused because the types in the inner square bracket (ie [int, Any] ) must be as many as the arguments of foo -- must they be so? -- but, apparently *args can be any number of arguments.

Prior to Python 3.10, the best you can do is type foo as Callable[..., None] , indicating it takes an arbitrary number of arbitrary arguments. You can't specify that at least one int argument must be passed as the first.

In Python 3.10, you can use typing.Concatenate and typing.ParamSpec to more closely match the type.

from typing import Concatenate, ParamSpec

P = ParamSpec('P')
def bar(f: Callable[Concatenate[int, P], None]):
    ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM