Reputation: 161
Let's say we want to type hint a function that takes in a positional argument and an arbitrary number of more arguments, e.g.
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 (i.e. [int, Any]
) must be as many as the arguments of foo
-- must they be so? -- but, apparently *args
can be any number of arguments.
Upvotes: 5
Views: 5857
Reputation: 530833
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]):
...
Upvotes: 4