Types

Callable Types

Callable annotations describe functions passed as values.

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

5
CALLBACK SLOTCallable[[int, str], bool]int,strbool
A Callable annotation describes the callback slot: this argument list must produce this return type.

Callable 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

12

Runtime 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 True

Notes

See also

Run the complete example

Example code

Expected output

5
12
True True

Execution time appears here after you run the example.