Sub topic 9
Callback protocols: typing callables with keyword arguments
This chapter assumes you can write a basic Protocol class, as in the earlier chapters. It also assumes you know Callable from collections.abc or typing.
Where Callable runs out
Callable[[str], bool] describes a function that takes one positional str and returns a bool. It has no syntax for parameter names, keyword-only parameters, default values, or *args and **kwargs with specific types.
Suppose callers rely on a retries keyword argument. Callable cannot say so. A callback protocol can, because a protocol that defines __call__ describes any object you can call with that signature. A plain function, a lambda, a bound method, and an instance of a class with __call__ can all qualify.
Defining a callback protocol
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 type checker compares the signature of log_handler with the signature of __call__, ignoring self. log_handler takes event and a keyword-only retries with a default, so it matches. log_handler never mentions Handler, which is structural subtyping at work.
What counts as compatible
The function must accept every call the protocol allows. Three rules cause most errors:
- Names matter for ordinary parameters. A caller of
Handlercould writehandler(event="x"). A function whose first parameter is callednamewould break that call, so the checker rejects it. - Keyword-only parameters must stay keyword-only or become more permissive. A function that requires
retrieswith no default is rejected, becausehandler("started")would fail. - Return types follow normal subtyping. A function returning
boolis fine. One returningNoneis not.
from typing import Protocol
class Handler(Protocol):
def __call__(self, event: str, *, retries: int = 0) -> bool: ...
def wrong_name(name: str, *, retries: int = 0) -> bool:
return True
def needs_retries(event: str, *, retries: int) -> bool:
return True
def run(handler: Handler) -> None:
handler("started")
run(wrong_name) # rejected: parameter "event" is called "name"
run(needs_retries) # rejected: "retries" has no defaultBoth calls to run work at runtime for the first call, since handler("started") passes the argument by position. The second call fails with a TypeError. The checker reports both before the program runs, which is the point of the protocol.
Loosening the name requirement
If callers always pass the argument by position, you can make it positional-only with /. Then any parameter name is accepted.
from typing import Protocol
class Formatter(Protocol):
def __call__(self, text: str, /) -> str: ...
def shout(message: str) -> str:
return message.upper()
def apply(fmt: Formatter, value: str) -> str:
return fmt(value)
print(apply(shout, "hello"))
print(apply(lambda s: s[::-1], "hello"))shout calls its parameter message, which would not match a text: str parameter that could be passed by keyword. The / removes that possibility, so the checker accepts it.
Callables with extra members
Because a callback protocol is a full protocol, you can add attributes next to __call__. A class instance with a counter fits, and a bare function does not unless it carries that attribute.
from typing import Protocol
class CountingHandler(Protocol):
calls: int
def __call__(self, event: str) -> bool: ...
class Counter:
def __init__(self) -> None:
self.calls = 0
def __call__(self, event: str) -> bool:
self.calls += 1
return True
def run(handler: CountingHandler) -> int:
handler("start")
return handler.calls
print(run(Counter()))Common mistakes
- Forgetting that parameter names are part of the contract when the parameter is not positional-only.
- Writing
def __call__(event: str)withoutself. The checker then readseventasself. - Expecting a runtime check. Callback protocols are for static checking, and
isinstancewould only confirm that__call__exists.
Exercise
A protocol defines def __call__(self, path: str, *, binary: bool = False) -> bytes: .... A function is declared def read(path: str, binary: bool = False) -> bytes. Will a type checker accept it, and why?
Show answer
Yes. The function accepts everything the protocol allows. It takes path by position or keyword, and binary can still be passed as a keyword. It also allows binary by position, which is more permissive than the protocol requires. The return type matches.