Define this:
class Foo(Protocol):
def __call__(self, x: int = ..., /) -> float:
...
then type hint foo
as Foo
instead of Callable[[int], float]
. Callback protocols allow you to:
define flexible callback types that are hard (or even impossible) to express using the
Callable[...]
syntax
and optional arguments are one of those impossible things to express with a normal Callable
. The /
at the end of __call__
‘s signature makes x
a positional-only parameter, which allows any passed function to bar
to have a parameter name that is not x
(your specific example of foo
calls it arg
instead). If you removed /
, then not only would the types have to line up as expected, but the names would have to line up too because you would be implying that Foo
could be called with a keyword argument. Because bar
doesn’t call foo
with keyword arguments, opting into that behavior by omitting the /
imposes inflexibility on the user of bar
(and would make your current example still fail because "arg" != "x"
).