What's the best way to specify that the Callable variable fn
takes *my_args
as arguments? Like this:
def test(fn: Callable([Tuple[any]], None),
*my_args: any) -> None:
fn(*myargs)
From the documentation on typing.Callable
:
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
.
So in your case where *args
is optional and ReturnType
is None
, use
fn: Callable[..., None]
P.s. I don't use type hints so please let me know if I've misunderstood anything.
Now with PEP 612 in Python 3.10, you can write this:
from typing import Callable, ParamSpec
P = ParamSpec("P")
def test(fn: Callable[P, None], *my_args: P.args, **my_kwargs: P.kwargs) -> None:
fn(*myargs, **my_kwargs)
Then any calls to test
will be properly type checked.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With