With the introduction of typing.Protocol
, MyPy (and other compliant type checkers) support the full call syntax natively via the __call__
special method.
Protocols can be used to define flexible callback types that are hard (or even impossible) to express using the Callable[...]
syntax, such as variadic, overloaded, and complex generic callbacks. (...)
Simply define a Protocol
whose __call__
method has the desired signature.
from typing import Protocol
class SomeCallable(Protocol):
def __call__(self, a: str, b: int, *args: float, kwargs: str) -> bytes: ...
def my_callable(a: str, b: int, *args: float, kwargs: str) -> bytes:
return b"Hello World"
def my_func(key: str) -> SomeCallable:
return my_callable
Note that the Protocol
's __call__
must include a self
parameter. This parameter is ignored when comparing other signatures against the Protocol
.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…