Python 3.5+Annotations & typingterm
Callable[[arg], ret]
callable
Annotation for callable objects. Callable[[A1, A2], R] takes A1, A2 and returns R. Callable[..., R] accepts any arguments.
Syntax
from typing import Callable
Callable[[ArgType, ...], ReturnType]
The inner brackets list the argument types, and only positional ones: keyword parameters, defaults and *args simply cannot be expressed with Callable — use a Protocol with a __call__ method instead. The ellipsis form means "any arguments at all", not "no arguments"; a no-argument callable is written with an empty inner list. Since Python 3.9 typing.Callable is deprecated in favour of collections.abc.Callable.
Examples
from typing import Callable
def apply(f: Callable[[int], int], x: int) -> int:
return f(x)
print(apply(lambda x: x * 2, 5)) # → 10
from typing import Callable
def run(cb: Callable[[], None]) -> None:
cb()
run(lambda: print('called')) # → called
from typing import Callable
def transform(data: list, fn: Callable[[int], int]) -> list:
return [fn(x) for x in data]
print(transform([1, 2, 3], lambda x: x ** 2)) # → [1, 4, 9]
print(callable(print)) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy