Search code examples
pythonpython-typingiterable-unpacking

How to type hint args and kwargs, if not unpacking, in most general form?


Let's say I want to pass args and kwargs to a function without using *args and **kwargs.

In the event, what is the most general type hint to use?

Is it Iterable for args and Mapping for kwargs?


Sample Code

Here is some sample code made using Python 3.8.

from typing import Mapping, Iterable

def foo(*args, **kwargs) -> None:
    pass

def foo_dispatcher(foo_args: Iterable, foo_kwargs: Mapping) -> None:
    foo(*foo_args, **foo_kwargs)

foo_dispatcher([0], {"ham": 1})

Solution

  • If you know your actual arguments and kwargs then you can obviously use the specifics, including TypedDict for the the arguments.

    In this most-general case you you can use Iterable and Mapping[str, object].

    For known functions over-typing is quite possible here, thanks to named non-keywords, variable length positional arguments, etc. You may not want to disallow def foo(a, b, c=4) being called as foo(1, b=1, c=2)