Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specifying *args for a Callable type hint

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)
like image 311
Dewamuval Avatar asked Nov 15 '19 19:11

Dewamuval


2 Answers

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 returning ReturnType.

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.

like image 141
wjandrea Avatar answered Sep 22 '22 03:09

wjandrea


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.

like image 33
CCCC_David Avatar answered Sep 21 '22 03:09

CCCC_David