Sub topic 8
Typing functions passed as arguments
This chapter assumes you can write annotated functions (def f(x: int) -> str), use built-in generics such as list[int], and run mypy or pyright on a file. Python treats functions as values, so you can pass one to another function, store it in a dict, or return it. Callable is the annotation that describes such a value.
The Callable syntax
Import Callable from collections.abc. This works on Python 3.9 and later. The older typing.Callable still works but is deprecated.
from collections.abc import Callable
def apply(func: Callable[[int], int], value: int) -> int:
return func(value)
def double(n: int) -> int:
return n * 2
print(apply(double, 21))
print(apply(lambda n: n + 1, 41))Callable[[int], int] has two parts. The first is a list of parameter types in square brackets. The second is the return type. The output is 42 twice.
Common forms:
| Annotation | Meaning |
|---|---|
| `Callable[[], None]` | Takes no arguments, returns nothing useful |
| `Callable[[str], int]` | Takes one `str`, returns an `int` |
| `Callable[[int, int], int]` | Takes two `int` values, returns an `int` |
| `Callable[..., int]` | Takes any arguments, returns an `int` |
| `Callable` (bare) | Same as `Callable[..., Any]`, so almost nothing is checked |
What the checker catches
If you pass a function whose signature does not fit, the checker reports it before the program 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 and returns strAt runtime this call raises AttributeError when 5.upper() is attempted. The checker finds the problem on the apply line.
Callbacks with no arguments
Use an empty parameter list when the callback takes nothing.
from collections.abc import Callable
def retry(action: Callable[[], bool], attempts: int) -> bool:
for _ in range(attempts):
if action():
return True
return False
state = {"calls": 0}
def flaky() -> bool:
state["calls"] += 1
return state["calls"] >= 3
print(retry(flaky, 5))Writing Callable[[], bool] is correct. Callable[bool] and Callable[[], ] are errors.
Returning functions
A function can build and return another function. The return annotation describes the inner function's signature.
from collections.abc import Callable
def make_multiplier(factor: int) -> Callable[[int], int]:
def multiply(n: int) -> int:
return n * factor
return multiply
triple = make_multiplier(3)
print(triple(5))The checker infers triple as Callable[[int], int], so triple("5") is flagged.
Compatibility rules
A function fits a Callable annotation when callers can safely use it as described. The rules differ for parameters and return values.
- Parameters accept wider types. If the checker expects
Callable[[int], str], a function takingobjectis fine. It accepts everyintand more. - Returns may be narrower. If the checker expects
Callable[[], int], a function returningboolis fine, becauseboolis a subclass ofint. - Extra optional parameters are fine. A function with defaults for its extra parameters still works when called with the expected arguments.
- Extra required parameters are an error. The caller would not supply them.
from collections.abc import Callable
def describe(value: object) -> str:
return f"got {value!r}"
def run(func: Callable[[int], str]) -> str:
return func(7)
print(run(describe))This passes the checker because object is wider than int.
Classes and methods are callables too
A class is callable because calling it creates an instance. A bound method is callable with self already filled in.
from collections.abc import Callable
def build(factory: Callable[[str], int], raw: str) -> int:
return factory(raw)
print(build(int, "42"))
print(build(len, "hello"))This prints 42 and then 5.
Naming callable types with aliases
Long Callable types are hard to read. Give them a name with an alias.
from collections.abc import Callable
Handler = Callable[[str], None]
handlers: dict[str, Handler] = {}
def register(event: str, handler: Handler) -> None:
handlers[event] = handler
def dispatch(event: str, payload: str) -> None:
handler = handlers.get(event)
if handler is not None:
handler(payload)
register("greet", print)
dispatch("greet", "hello")The is not None test narrows handler from Handler | None to Handler before the call. This prints hello.
When Callable is not enough
Callable only describes positional parameters. It cannot express keyword-only arguments, default values, or parameter names. When you need those, write a Protocol with a __call__ method.
from typing import Protocol
class Formatter(Protocol):
def __call__(self, text: str, *, upper: bool = False) -> str: ...
def plain(text: str, *, upper: bool = False) -> str:
return text.upper() if upper else text
def render(fmt: Formatter) -> str:
return fmt("hello", upper=True)
print(render(plain))This prints HELLO. The protocol is strict about names. If plain called its first parameter s instead of text, the checker would reject it, because a caller could write fmt(text="hello").
Common mistakes
- Forgetting the inner brackets.
Callable[int, int]is wrong. WriteCallable[[int], int]. - Using bare
Callable. It silently turns off checking of the arguments and return value. - Using
...when you know the signature.Callable[..., int]accepts any function that returnsint, including ones that cannot be called the way you call them. - Expecting
__name__. Not every callable has__name__, so checkers rejectfunc.__name__on aCallable. Usegetattr(func, "__name__", "?")if you need it. - Annotating a decorator as
Callable[..., Any]everywhere. This works, but it erases the wrapped function's signature. Precise decorator typing needs tools covered in later chapters.
Summary
Callable[[A, B], R]describes a function takingAandBand returningR.- Use
[]for no parameters and...only when the parameters truly vary. - Parameters accept wider types and returns may be narrower.
- Classes and bound methods count as callables.
- Use an alias to name long callable types, and a
Protocolwith__call__for keyword arguments or defaults.
Exercise
Write the type annotation for a parameter named predicate that accepts any function taking one str and returning a bool. Then say whether predicate=str.isdigit would pass a type checker.
Show answer
The annotation is predicate: Callable[[str], bool], with from collections.abc import Callable. Passing str.isdigit is accepted. It is a function that takes a str (the self argument) and returns a bool.
Exercise
A function expects Callable[[int, int], int]. You pass def add(a: int, b: int, c: int) -> int. Does the checker accept it? What change would make it acceptable?
Show answer
No. add has an extra required parameter c, and the caller supplies only two arguments. Giving c a default, as in c: int = 0, makes it acceptable.
Exercise
Why would you choose a Protocol with __call__ over Callable[[str], str] for a function that must be callable as fmt("x", upper=True)?
Show answer
Callable cannot describe keyword arguments or default values. A Protocol with def __call__(self, text: str, *, upper: bool = False) -> str states the keyword-only upper parameter exactly, so the checker verifies it.