Types
Callable Types
Use Callable[[Arg], Return] for function-shaped values. The callback is passed in and called by the receiving function.
Source
from collections.abc import Callable
def apply_twice(value: int, func: Callable[[int], int]) -> int:
return func(func(value))
def add_one(number: int) -> int:
return number + 1
print(apply_twice(3, add_one))Output
5Callable annotations are structural: an object with __call__ can also satisfy the shape.
Source
class Doubler:
def __call__(self, number: int) -> int:
return number * 2
print(apply_twice(3, Doubler()))Output
12Runtime callability is a separate question from static annotation. callable() checks whether Python can call the object.
Source
print(callable(add_one), callable(Doubler()))Output
True TrueNotes
- Use
Callable[[Arg], Return]for simple function-shaped values. - The annotation documents how the callback will be called.
- For complex call signatures, protocols can be clearer.
See also
- prerequisite: Functions
- prerequisite: Callable Objects
- related: Protocols
Run the complete example
Expected output
5
12
True True
Execution time appears here after you run the example.