Sub topic 8
Typing functions passed as arguments
This chapter assumes you can write annotated functions, use list[int] and X | None, and run mypy or pyright. It covers how to describe a function that is passed to another function.
Why a plain `function` type is not enough
Python lets you pass functions around like any other value. A checker needs to know what shape of function is acceptable. If you annotate the parameter as object or Any, the checker cannot catch a callback with the wrong arguments. Callable fixes this.
The Callable syntax
Import Callable from collections.abc. It takes two parts: a list of parameter types, then the return type.
from collections.abc import Callable
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
print(apply(lambda n: n * 2, 21))Callable[[int], int] means "a function that takes one int and returns an int". The parameter types go inside their own square brackets. The return type comes last, outside them.
| Annotation | Meaning |
|---|---|
| `Callable[[], None]` | No arguments, returns nothing |
| `Callable[[str], int]` | One `str`, returns `int` |
| `Callable[[int, int], bool]` | Two `int` arguments, returns `bool` |
| `Callable[..., int]` | Any arguments, returns `int` |
Use ... only when the parameters truly vary. It switches off checking of the arguments.
A callback with a different return type
The callable's return type does not have to match the surrounding function. This helper runs a transformation over each item.
from collections.abc import Callable
def transform_all(items: list[str], func: Callable[[str], int]) -> list[int]:
return [func(item) for item in items]
print(transform_all(["a", "bb", "ccc"], len))Built-in functions such as len and named functions you define yourself work as well as lambdas, as long as their signatures match.
What the checker reports
A mismatched callback is an error before the code runs.
from collections.abc import Callable
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
def shout(text: str) -> str:
return text.upper()
apply(shout, 5) # checker error: shout takes str, not intPython still raises an error at runtime here, but only when .upper() is called on an int. The checker reports the problem earlier, at the call site.
Common errors
- Forgetting the inner brackets.
Callable[int, int]is invalid. WriteCallable[[int], int]. - Importing from
typing.typing.Callablestill works but is deprecated. Prefercollections.abc.Callable. - Using
Callablefor keyword arguments.Callableonly describes positional parameters. For keyword names or defaults, aProtocolwith a__call__method is needed. - Mixing up the return type. A callback that returns
NoneisCallable[[...], None], not a callable with no return annotation.
Exercise
Write the annotation for a parameter predicate that accepts a function taking a str and returning a bool.
Show answer
predicate: Callable[[str], bool], with from collections.abc import Callable at the top of the file.