In this lesson, you will learn how to enforce specific function signatures across your codebase by defining Protocol classes that represent callable objects.
Moving Beyond Simple Type Hints
While you may be familiar with the Callable[[ArgType], ReturnType] type hint, sometimes you need to enforce a stricter interface. By defining a Protocol with a __call__ method, you can create a clear contract for objects that must behave like a function. This is particularly useful when you need to pass objects that have complex internal states but still need to be invoked as a function.
Defining the Protocol
To define a callable Protocol, you use the __call__ method. Python’s static type checkers (like Mypy) treat classes containing this specific dunder method as "callable" if they match the signature provided.
Consider a scenario where you require a logging function that accepts a string and returns nothing:
from typing import Protocol
class Logger(Protocol):
def __call__(self, message: str) -> None:
...
def execute_task(logger: Logger):
logger("Task started")
# This works because the class implements __call__
class ConsoleLogger:
def __call__(self, message: str) -> None:
print(f"[LOG]: {message}")
execute_task(ConsoleLogger())
Why Use This Instead of Callable?
Using a Protocol offers two major advantages over the generic Callable:
- Readability: You can name your Protocol (e.g.,
Logger,DataTransformer), making it clear what kind of function is expected, rather than relying on a genericCallable[[str], None]signature. - Structural Integrity: If your callable needs to carry extra metadata or attributes (like a
versionattribute or anenable()method), aProtocolallows you to define those requirements alongside the__call__signature. A standardCallabletype hint cannot enforce the presence of these additional attributes.
By using Protocol for callables, you bridge the gap between simple functional requirements and robust object-oriented interfaces.
Key Takeaway: By defining a __call__ method within a Protocol, you create a precise, named contract for any object that needs to act like a function, ensuring structural consistency across your architecture.