Sub topic 10
Type hints for *args and **kwargs
This chapter assumes you can write functions that use *args and **kwargs, and that you know basic annotations such as int, str, and -> None. The examples use Python 3.12. Type hints don't change how the code runs. A checker such as mypy or pyright reads them and reports mismatches before you run the program.
The annotation describes each item
You annotate *args and **kwargs with the type of one element, not the type of the whole collection.
def total(*args: int) -> int:
return sum(args)
def show(**kwargs: float) -> None:
for key, value in kwargs.items():
print(f"{key}={value}")
print(total(1, 2, 3)) # 6
show(width=2.5, height=4)
# width=2.5
# height=4*args: int means every extra positional argument must be an int. Inside the function, args has the type tuple[int, ...]. **kwargs: float means every extra keyword value must be a float. Inside the function, kwargs has the type dict[str, float]. The keys are always strings.
| Signature | Annotation applies to | Type inside the function |
|---|---|---|
| `*args: int` | each extra positional argument | `tuple[int, ...]` |
| `**kwargs: float` | each extra keyword value | `dict[str, float]` |
Don't write *args: tuple[int, ...]. That declares that each argument is itself a tuple of integers, which is almost never what you mean.
Mixed types and Any
If the extra arguments can have different types, use a union or Any.
from typing import Any
def label(*parts: int | str) -> str:
return "-".join(str(part) for part in parts)
def configure(**settings: Any) -> dict[str, Any]:
return dict(settings)
print(label("user", 42)) # user-42
print(configure(debug=True, retries=3))
# {'debug': True, 'retries': 3}Any turns off checking for those values. Use it when the values really are unrestricted, such as settings passed to another library. Otherwise a union keeps the checker useful.
Typing a wrapper with ParamSpec
A decorator that accepts *args and **kwargs and forwards them works with any function. A simple hint such as Callable[..., Any] throws away the original signature, so the checker can no longer verify calls to the decorated function. ParamSpec captures the full parameter list and reuses it.
import functools
from typing import Callable, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def log_calls(func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"calling {func.__name__} with {args} {kwargs}")
return func(*args, **kwargs)
return wrapper
@log_calls
def add(a: int, b: int = 0) -> int:
return a + b
print(add(1, b=2))
# calling add with (1,) {'b': 2}
# 3Three parts work together here:
Pstands for the parameters of the wrapped function.Rstands for its return type.P.argsandP.kwargsare the only valid annotations for the wrapper's*argsand**kwargs. You must use them as a pair.
After decoration, add keeps the signature (a: int, b: int = 0) -> int. A call such as add("x") is still flagged by the checker.
Named keyword arguments with Unpack
**kwargs: str forces every keyword to have the same value type. Sometimes each keyword has its own type. A TypedDict combined with Unpack describes that. Type checkers accept this form from Python 3.12 (PEP 692). On older versions, import Unpack from typing_extensions.
from typing import TypedDict, Unpack
class Options(TypedDict, total=False):
color: str
size: int
def draw(shape: str, **options: Unpack[Options]) -> str:
color = options.get("color", "black")
size = options.get("size", 1)
return f"{shape} {color} {size}"
print(draw("circle", size=3)) # circle black 3
# draw("circle", sise=3) -> checker error: unexpected keyword "sise"
# draw("circle", size="3") -> checker error: "size" must be intHere total=False makes every key optional. Without it, callers must supply all keys. The checker now catches misspelled keywords and wrong value types. It also gives editors something to autocomplete.
Choosing an annotation
- All extras share one type:
*args: intor**kwargs: str. - Extras are unrestricted:
Any, used sparingly. - The function is a decorator or wrapper:
ParamSpecwithP.argsandP.kwargs. - The keywords are a known set with different types:
Unpack[TypedDict].
Exercise
Add type hints to this function so that every extra positional argument must be a string and every extra keyword value must be a bool. Then state what parts and flags are inside the function.
def join_all(sep, parts, *flags):
return sep.join(parts)
Show answer
def join_all(sep: str, parts: str, *flags: bool) -> str: return sep.join(parts) Inside the function, parts has the type tuple[str, ...] and flags has the type dict[str, bool]. The annotations describe one element each, not the whole collection.