Sub topic 9
Callback protocols: typing callables with keyword arguments
This chapter assumes you can write Python functions and classes, and that you know basic type hints. It also assumes you have used a static type checker such as mypy or pyright, and that you have seen typing.Protocol for methods. Here the same idea is applied to functions.
Where Callable runs out
A callback is a function you pass to other code, so that code can call it later. The usual annotation is Callable[[ArgTypes], ReturnType]. It works well when every argument is positional.
from collections.abc import Callable
def run(handler: Callable[[str, int], bool]) -> None:
handler("started", 2)
def log_handler(event: str, *, retries: int = 0) -> bool:
print(f"{event} (retries={retries})")
return True
run(log_handler) # type checker error, and TypeError at runtimeCallable[[str, int], bool] says "a callable taking two positional arguments". log_handler takes retries only by keyword, so the call handler("started", 2) fails with a TypeError. The checker rejects the call, which is correct.
The real problem is the other direction. Callable cannot say "takes a string, plus an optional keyword-only retries". It has no syntax for:
- keyword-only parameters
- parameter names
- default values
- a mix of required and optional parameters
If your callers use handler("started", retries=2), you cannot describe that contract with Callable.
Defining a callback protocol
A callback protocol is a protocol with a __call__ method. Any object whose call signature is compatible with that method satisfies it. Functions, lambdas, bound methods and instances of classes that define __call__ all qualify.
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
def log_handler(event: str, *, retries: int = 0) -> bool:
print(f"{event} (retries={retries})")
return True
def run(handler: Handler) -> None:
handler("started", retries=2)
run(log_handler)The self in the protocol's __call__ is not part of the contract. The checker compares everything after self with the signature of the function you pass in. Running the script prints started (retries=2).
Nothing here inherits from Handler. This is the same structural rule you saw for method protocols: the shape of the call decides compatibility.
Classes with state also qualify
A callable object can hold state, such as a counter, and still satisfy the protocol.
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
class CountingHandler:
def __init__(self) -> None:
self.calls = 0
def __call__(self, event: str, *, retries: int = 0) -> bool:
self.calls += 1
return retries < 3
handlers: dict[str, Handler] = {}
def register(name: str, handler: Handler) -> None:
handlers[name] = handler
counter = CountingHandler()
register("count", counter)
print(handlers["count"]("boot", retries=1))
print(counter.calls)This prints True and then 1. The registry stores Handler values and knows nothing about CountingHandler. The calls attribute is invisible through the Handler type, so code that holds a Handler cannot read it. That is the point of the narrow contract.
How the checker compares signatures
The checker asks whether every call that is valid for the protocol's __call__ is also valid for your function. The rules follow from that question.
| Aspect | Rule |
|---|---|
| Parameter types | Contravariant. Your function may accept a wider type than the protocol states. |
| Return type | Covariant. Your function may return a narrower type than the protocol states. |
| Parameter names | Must match for any parameter a caller could pass by keyword. |
| Defaults | If the protocol parameter has a default, yours must also have one. |
| Extra parameters | Allowed only if they have defaults (or are `*args` / `**kwargs`). |
| Positional-only | Names do not matter, because callers cannot pass them by keyword. |
Compatible and incompatible functions
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
# Accepted: wider parameter type, extra parameter with a default.
def lenient(event: object, *, retries: int = 0, verbose: bool = False) -> bool:
return True
# Rejected: the keyword is named "attempts", not "retries".
def renamed(event: str, *, attempts: int = 0) -> bool:
return True
# Rejected: "retries" has no default, so handler("x") would fail.
def required(event: str, *, retries: int) -> bool:
return True
# Rejected: returns None, not bool.
def wrong_return(event: str, *, retries: int = 0) -> None:
return None
a: Handler = lenient
b: Handler = renamed # error
c: Handler = required # error
d: Handler = wrong_return # errorEach rejected case maps to a real failure. A caller writing handler("x", retries=2) would break with renamed. A caller writing handler("x") would break with required.
The checker's decision for each parameter follows this path.
The parameter-name trap
Names matter because Python allows any positional-or-keyword parameter to be passed by name. If the protocol declares event: str, a caller may write handler(event="started"). A function whose first parameter is evt would break that call, so the checker rejects it.
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
def short_name(evt: str, *, retries: int = 0) -> bool: # rejected
return True
h: Handler = short_nameIf you do not want callers to use keyword names, make the parameter positional-only with a / in the protocol. Then implementers can name it anything.
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, /, *, retries: int = 0) -> bool: ...
def short_name(evt: str, *, retries: int = 0) -> bool: # accepted
return True
h: Handler = short_nameThe / comes from PEP 570 and needs Python 3.8 or later. The older convention of a double-underscore prefix (__event) has the same effect in type checkers.
Callable or callback protocol?
Use Callable when the signature is simple and positional. Use a callback protocol when you need any of the features in the table.
| Need | `Callable[...]` | Callback protocol |
|---|---|---|
| Positional parameters with types | Yes | Yes |
| Keyword-only parameters | No | Yes |
| Default values | No | Yes |
| Parameter names callers can use | No | Yes |
| A reusable, documented name | Only via a type alias | Yes, the class itself |
| Extra members next to `__call__` | No | Yes |
The last row is easy to overlook. A callback protocol can declare other members besides __call__, such as a reset() method. Then only objects that are both callable and have that method qualify. Plain functions fail that check unless they carry the attribute.
Common pitfalls
- Forgetting that names are part of the contract. Most rejected callbacks in practice differ only in a parameter name.
- Writing the protocol with a body. Use
...for the method body. A protocol is a description, not an implementation. - Using
isinstancewith a callback protocol. If you add@runtime_checkable,isinstance(obj, Handler)checks only that__call__exists. It does not check names, defaults or types. Every function passes, whatever its signature. - Mixing up variance. Making your parameter types narrower than the protocol's is an error, not a refinement. A function that accepts only
strcannot stand in for a protocol that passesobject. - Expecting runtime enforcement. All the checks in this chapter happen in the type checker. At runtime Python only fails when a call actually does not fit.
Summary of the working model
A callback protocol is a protocol whose only required member is __call__. The checker treats the signature after self as the contract and accepts any callable that can be called in every way the contract allows. Parameter names, keyword-only markers and defaults are part of that contract, which is why this form can describe callbacks that Callable cannot.
Exercise
Given this protocol, which of the two functions is accepted by a type checker, and why is the other rejected? class Sender(Protocol): def _call(self, message: str, *, timeout: float = 1.0) -> bool: ... def senda(message: str, *, timeout: float = 5.0, secure: bool = True) -> bool: ... def send_b(message: str, timeout: float) -> bool: ...
Show answer
senda is accepted. It has the same required parameter, the same keyword-only timeout with a default, and an extra parameter secure that has a default, so every call valid for Sender is valid for senda. send_b is rejected. Its timeout is positional-or-keyword with no default, so Sender's call sender("hi") would fail because timeout is missing, and it is no longer keyword-only.
Exercise
Change the Handler protocol so that the function def on_event(name: str, *, retries: int = 0) -> bool is accepted even though its first parameter is called name rather than event. Show the protocol.
Show answer
Make the first parameter positional-only by adding a slash: class Handler(Protocol): def _call_(self, event: str, /, *, retries: int = 0) -> bool: ... Callers can no longer pass event by keyword, so the implementer's parameter name does not matter. The keyword-only retries must still keep its name.