Sub topic 10
Type hints for *args and **kwargs
This chapter shows how to annotate functions that take *args and **kwargs. It also covers the special tools Python provides for the harder cases: precise keyword names with Unpack, and decorators that keep the wrapped function's signature with ParamSpec.
I assume you already know how *args and **kwargs collect arguments, how call-site unpacking works, and how wrappers forward arguments. You should also know basic annotations such as x: int and -> str. Examples use Python 3.12 unless noted. Where an older version needs something different, the text says so.
What an annotation on *args means
An annotation on *args describes each individual argument, not the collection. Inside the function, args is always a tuple, but you write the type of one element.
def total(*args: int) -> int:
return sum(args)
print(total(1, 2, 3)) # 6
print(total()) # 0A type checker reads *args: int as "zero or more int values", and inside the body it treats args as tuple[int, ...]. The same rule applies to **kwargs. The annotation describes each value, and the keys are always str. Inside the body, kwargs: str means dict[str, str].
def show(**kwargs: str) -> None:
for key, value in kwargs.items():
print(f"{key}={value}")
show(name="Ada", city="London")
# name=Ada
# city=LondonThe table below summarizes the mapping.
| Annotation in the signature | Type of the variable inside the function | What callers may pass | Column | Column |
|---|---|---|---|---|
| `*args: int` | `tuple[int, ...]` | Any number of `int` positional arguments | ||
| `**kwargs: str` | `dict[str, str]` | Any keyword arguments whose values are `str` | ||
| `*args: int \ | str` | `tuple[int \ | str, ...]` | Positional arguments, each an `int` or a `str` |
| `**kwargs: Any` | `dict[str, Any]` | Any keyword arguments |
Annotations are not enforced at runtime
Python stores annotations but does not check them when the function runs. Only a separate type checker such as mypy or pyright reports mismatches.
def count(*args: int) -> int:
return len(args)
print(count("a", "b")) # 2, no error at runtimeA checker would flag the call count("a", "b"), but the interpreter runs it without complaint. You can inspect what Python stored.
import inspect
def configure(*args: int, **kwargs: str) -> None:
pass
print(configure.__annotations__)
# {'args': <class 'int'>, 'kwargs': <class 'str'>, 'return': None}
print(inspect.signature(configure))
# (*args: int, **kwargs: str) -> NoneNotice that __annotations__ records int, not tuple[int, ...]. The stored annotation is exactly what you wrote, which is the element type.
Mixed types and the Any escape hatch
When the extra arguments can have different types, use a union. Python 3.10 and later accept the | form.
def join_all(*parts: str | int, sep: str = "-") -> str:
return sep.join(str(part) for part in parts)
print(join_all("a", 1, "b")) # a-1-b
print(join_all("x", "y", sep="/")) # x/yHere sep is keyword-only because it follows *parts. It gets its own annotation like any other parameter.
If you truly accept anything, use Any. This is common in code that passes arguments along to somewhere else.
from typing import Any
def pass_through(*args: Any, **kwargs: Any) -> None:
print(args, kwargs)
pass_through(1, "two", three=3)
# (1, 'two') {'three': 3}Any switches off checking for those values. It is a reasonable choice when you cannot know the types, but it hides mistakes. Use a narrower type when you can.
Combining with positional-only and keyword-only parameters
Hints on / and bare * parameters work the same as everywhere else. The separators themselves take no annotation.
def g(a: int, /, b: str, *, c: float) -> tuple[int, str, float]:
return a, b, c
print(g(1, "x", c=2.5)) # (1, 'x', 2.5)A named *args also ends the positional parameters, so you do not need a bare * after it.
def h(first: str, *rest: int, flag: bool = False, **extra: float) -> None:
print(first, rest, flag, extra)
h("a", 1, 2, flag=True, ratio=0.5)
# a (1, 2) True {'ratio': 0.5}Every kind of parameter has its own annotation, and the checker validates each call value against the slot it lands in.
Typing specific keyword names with Unpack
**kwargs: str says every keyword value is a str, but it cannot say that the function accepts only color and size, or that size must be an int. For that, describe the allowed keys with a TypedDict and mark the parameter with Unpack. This form needs Python 3.12. On older versions, import Unpack from the typing_extensions package instead.
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", color="red")) # circle red 1
print(draw("square")) # square black 1A checker now accepts draw("circle", color="red", size=3). It rejects draw("circle", colour="red") because colour is not a key of Options. It also rejects draw("circle", size="big") because size must be an int. Editors can autocomplete the keyword names too.
Here total=False makes every key optional. You can mix required and optional keys with Required and NotRequired.
from typing import NotRequired, TypedDict, Unpack
class Connection(TypedDict):
host: str
port: NotRequired[int]
timeout: NotRequired[float]
def connect(**params: Unpack[Connection]) -> str:
port = params.get("port", 5432)
return f"{params['host']}:{port}"
print(connect(host="db.local")) # db.local:5432
print(connect(host="db.local", port=6000)) # db.local:6000Calling connect() with no host is an error for the checker, because host is required. At runtime, params is still a plain dict, so nothing stops a wrong call from executing.
Typing a decorator that preserves the signature
The wrapper pattern from the earlier chapter, wrapper(*args, **kwargs), works for any function. The cost is that annotating it with Any makes the decorated function lose its real signature, so a checker can no longer verify calls to it. ParamSpec solves this. It captures the full parameter list of the wrapped function and reuses it.
import functools
from collections.abc import Callable
from typing import 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}
# 3Read the types as follows:
Pstands for "the parameters of the decorated function", including names, defaults, and kinds.Rstands for its return type.P.argsandP.kwargsare the types of*argsand**kwargsfor that parameter list. You must use them as a pair, on a*argsand**kwargsof the same function.Callable[P, R]as the return type tells the checker that the result takes the same parameters and returns the same type as the original.
After decoration, add("x") is still flagged by the checker, even though add is now the wrapper.
On Python 3.12 and later you can skip the ParamSpec(...) and TypeVar(...) lines and declare the type variables in the function header. Both styles mean the same thing.
import functools
from collections.abc import Callable
def log_calls[**P, R](func: Callable[P, R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
print(f"calling {func.__name__}")
return func(*args, **kwargs)
return wrapperDecorators that add or remove an argument
When the wrapper supplies one leading argument itself, use Concatenate. It describes "one fixed parameter, then everything in P".
import functools
from collections.abc import Callable
from typing import Concatenate, ParamSpec, TypeVar
P = ParamSpec("P")
R = TypeVar("R")
def with_prefix(func: Callable[Concatenate[str, P], R]) -> Callable[P, R]:
@functools.wraps(func)
def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:
return func("LOG", *args, **kwargs)
return wrapper
@with_prefix
def write(prefix: str, message: str, *, end: str = "\n") -> None:
print(f"[{prefix}] {message}", end=end)
write("hello") # [LOG] helloThe decorated write takes only message and the keyword-only end. The checker knows that the prefix parameter has been removed from the public signature.
Typing a fixed set of positional arguments
Sometimes *args is not "any number of the same type" but a known sequence of different types. Python 3.11 added unpacked tuple types for this.
| Annotation | Meaning |
|---|---|
| `*args: int` | Any number of `int` values |
| `*args: *tuple[int, str]` | Exactly two arguments: an `int`, then a `str` |
| `*args: *tuple[int, *tuple[str, ...]]` | An `int`, followed by any number of `str` values |
These forms are rarely needed. If the argument count is fixed, ordinary named parameters are clearer. They are most useful with TypeVarTuple, which lets a generic function work with a variable number of different types.
Overloads for different call shapes
Sometimes a function behaves differently depending on which arguments are given, and the return type changes with them. typing.overload lets you declare each shape separately. You can combine it with *args and **kwargs when the implementation is flexible.
from typing import overload
@overload
def first(*items: int) -> int: ...
@overload
def first(*items: str) -> str: ...
def first(*items):
return items[0]
print(first(3, 4)) # 3
print(first("a")) # aThe two @overload stubs are for the checker only. The final definition without a decorator is the one that runs, and it should handle every declared case. A checker will say that first(3, 4) returns int and first("a") returns str.
Common mistakes
- Annotating the container instead of the element. Write
*args: int, not*args: tuple[int, ...]. Likewise, write**kwargs: int, not**kwargs: dict[str, int]. - Expecting runtime checks. Annotations never raise errors by themselves. If you need validation at runtime, check the values yourself or use a validation library.
- Using
Anyin a decorator wrapper.wrapper(*args: Any, **kwargs: Any) -> Anymakes the decorated function accept anything and return anything. UseParamSpecto keep the original signature. - Using
P.argswithoutP.kwargs. The two belong together. A checker reports an error if a wrapper uses only one of them. - Using
Unpackon*args-style names.Unpack[TypedDict]is valid only for**kwargs. For*args, the matching tool is an unpacked tuple type, as in*args: *tuple[int, str]. - Forgetting that Unpack needs 3.12. On Python 3.11 and earlier,
from typing import UnpackraisesImportError. Import it fromtyping_extensionsinstead. - Declaring one wide TypedDict for many functions. If functions accept different keys, a shared
TypedDictlets callers pass keys that a given function ignores. Define aTypedDictper function or per group of related functions.
Choosing an approach
| Situation | Annotation to use |
|---|---|
| Many values of one type, such as `sum`-like helpers | `*args: int` |
| Extra options that all have the same value type | `**kwargs: str` |
| Specific option names with different value types | `**kwargs: Unpack[Options]` |
| Forwarding to another callable you do not control | `*args: Any, **kwargs: Any` |
| Decorator that keeps the wrapped signature | `ParamSpec` with `P.args` and `P.kwargs` |
| Decorator that adds or removes a leading parameter | `Concatenate[X, P]` |
| A fixed sequence of mixed types | `*args: *tuple[int, str]`, or plain named parameters |
Summary
- An annotation on
*argsor**kwargsdescribes one element or one value. The container type is implied. - Python stores annotations but does not enforce them. Type checkers do the enforcing.
Unpack[SomeTypedDict]on**kwargstypes specific keyword names and their value types.ParamSpecwithP.argsandP.kwargslets a decorator keep the signature of the function it wraps.Concatenatehandles added or removed leading parameters.- Prefer a specific type over
Any, and prefer named parameters when the argument list is fixed.
Exercise
A teammate writes def scale(*factors: tuple[float, ...]) -> float: and calls scale(1.5, 2.0). A type checker rejects the call. What is wrong, and what is the corrected signature?
Show answer
The annotation on *factors describes each individual argument, so tuple[float, ...] says that every argument must be a tuple of floats. The values 1.5 and 2.0 are floats, so the call is rejected. The corrected signature is def scale(*factors: float) -> float:. Inside the function, factors is then seen as tuple[float, ...].
Exercise
Write a function make_user(name: str, **fields) so that a type checker accepts only the optional keyword arguments age (an int) and email (a str). Show the type definition and the signature, and say which Python version the standard-library import needs.
Show answer
Define a TypedDict with optional keys and mark **fields with Unpack:
from typing import TypedDict, Unpack
class UserFields(TypedDict, total=False):
age: int
email: str
def makeuser(name: str, fields: Unpack[UserFields]) -> dict:
return {"name": name, fields}
Importing Unpack from typing needs Python 3.12. On older versions, import it from `typingextensions`.
Exercise
A decorator is written as def timed(func): def wrapper(*args, **kwargs): ... return func(*args, **kwargs); return wrapper. Add annotations so that a checker still knows the decorated function's real parameters and return type. Which names are required, and what must go on the wrapper's *args and **kwargs?
Show answer
Use a ParamSpec P and a TypeVar R. The signature becomes def timed(func: Callable[P, R]) -> Callable[P, R]:, and the wrapper becomes def wrapper(*args: P.args, **kwargs: P.kwargs) -> R:. You need Callable (from collections.abc), ParamSpec and TypeVar (from typing). P.args goes on *args and P.kwargs goes on **kwargs, and both must be used together.