Typed callbacks
A function accepts a callback whose input and output types are known.
Python · Type Alias
Callable describes the signature of a function or other callable object: its parameter types and return type. Use collections.abc.Callable in modern annotations; typing.Callable is deprecated.
Use Callable to describe the input types and return type of a function or other callable object. The argument specification is either a list of types, a parameter specification, a concatenation, or an ellipsis when only the return type matters.
collections.abc.Callable[[ArgType1, ArgType2, ...], ReturnType]
collections.abc.Callable[..., ReturnType]
collections.abc.Callable[ParamSpec, ReturnType]
collections.abc.Callable[Concatenate[ArgType1, ..., ParamSpec], ReturnType]| Name | Type | Description |
|---|---|---|
arg_types | list[type] | ParamSpec | Concatenate[...] | Ellipsis | Argument specification: a list of parameter types, ParamSpec, Concatenate, or ellipsis. |
return_type | type | The callable's result type; it must be one type. |
The type of the value produced by the callable.
from collections.abc import Callable
def apply_twice(function: Callable[[int], int], value: int) -> int:
return function(function(value))
print(apply_twice(lambda number: number + 1, 3))The annotation requires a callable that accepts an int and returns an int.
A function accepts a callback whose input and output types are known.
A decorator forwards an arbitrary callable's parameters while preserving their relationship.
A decorator adds or removes leading parameters from another callable.
An API accepts any callable but requires a known result type.
Callable[[int], str] describes a callable receiving one int and producing a str. The first subscription value is the argument-type list, and the second is the single return type.
Follow-up: How would you describe a callable with an unknown parameter list but a known result? Use Callable[..., ReturnType], replacing ReturnType with the required result type.
Callable[..., ReturnType] uses an ellipsis for the argument specification. It records the return type while allowing any number of arguments.
Follow-up: What does an unparameterized Callable mean? It is equivalent to Callable[..., Any], and the documentation also equates it with collections.abc.Callable.
The modern spelling is collections.abc.Callable; typing.Callable is documented as its deprecated alias. Callable also cannot model keyword-only parameters, overloaded functions, or variadic signatures.
Follow-up: How can dependent callable parameters be represented? Use ParamSpec, or Concatenate when parameters are added or removed.
collections.abc.CallableParamSpecConcatenateAny