What is the typing signature for print or similar function which takes a variable number of arguments of any type, when defined as a Callable parameter?
Concretely, what is the declaration of output_function
here?
def f(x: str, output_function=print): output_function(x)
Update: clarified as a Callable parameter.
Advertisement
Answer
From 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)
So print
would be:
from typing import Any, IO def print(*args: Any, sep: str = ' ', end: str = 'n', file: IO = sys.stdout, flush: bool = False) -> None:
I don’t think you can apply this to a Callable
though. From the docs for typing
,
There is no syntax to indicate optional or keyword arguments; such function types are rarely used as callback types.
Callable[..., ReturnType]
(literal ellipsis) can be used to type hint a callable taking any number of arguments and returningReturnType