In the middle of the desert you can say anything you want

28 Feb 2023

Python Callable Protocols for complex Callable typing

If you need to add typing to a complex Callable, with, say, parameter names etc., there are Callback Protocols.

# NB "self" is included!
class Combiner(Protocol):
    def __call__(self, *vals: bytes, maxlen: Optional[int] = None) -> list[bytes]: ...

def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
    for item in data:

Python 3.7 needs typing_extensions, 3.8+ support it natively.

See also: python typing signature (typing.Callable) for function with kwargs - Stack Overflow

Nel mezzo del deserto posso dire tutto quello che voglio.