A task finishes and needs to send a notification. In normal use, the message should appear in the terminal. In tests, it should go into a list so I can assert on it. Someone familiar with Java might first define a Sender interface and have both senders implement it. In Python, do I need to declare the interface first?1
Can I swap senders as long as I can call send()?
Here notify decides what message to send, and the sender decides where it goes.
class ConsoleSender:
def send(self, message: str) -> None:
print(message)
class RecordingSender:
def __init__(self) -> None:
self.messages: list[str] = []
def send(self, message: str) -> None:
self.messages.append(message)
def notify(sender):
sender.send("任务完成")
notify(ConsoleSender()) # 在终端显示“任务完成”
recording = RecordingSender()
notify(recording)
assert recording.messages == ["任务完成"]
Both calls execute the same line, sender.send("任务完成") (“task complete”). Python looks for the method on the supplied object and calls it with the given arguments. That is duck typing: which objects the code accepts depends on what it actually does with them. Pass an ordinary list and the error occurs on the call to send, because a list has no such method.2
This already uses dependency injection (DI). The sender is an object notify depends on to do its work. The caller creates it and passes it as an argument. If ConsoleSender() were hard-coded inside notify, a test that wanted to collect messages would somehow have to replace the internally created object. Here the test passes recording itself and can check directly what it received.
How can an interface flag the wrong object before the program runs?
Looking only at def notify(sender), you have to read the body to find out which methods a sender needs. Python’s standard typing.Protocol can express this agreement on the parameter. Keep both senders above and change only the definition of notify:
from typing import Protocol
class Sender(Protocol):
def send(self, message: str) -> None: ...
def notify(sender: Sender) -> None:
sender.send("任务完成")
Now a static type checker such as mypy accepts notify(RecordingSender()) and flags notify([]) as a type error. It can see that RecordingSender provides a send method with a compatible signature, even though the class never declared that it inherits from Sender. PEP 544 calls this “structural subtyping (static duck typing)”.3 If you run the program directly in Python, the parameter annotation alone does not perform that check.
The interface contains only send because that is the only method notify uses. Tests can still read RecordingSender.messages to check results. Other senders do not need to store messages to work with notify. A third-party sender added later can be passed directly if it has a compatible method.
When is an abstract base class worthwhile?
The difference between an interface and an abstract class is easier to see when several senders start sharing code.4 Suppose every sender needs to strip whitespace from both ends of the message, skip an empty message, and choose its own delivery mechanism only at the last step. An abstract base class (ABC) can implement that shared process and leave the final step to subclasses.
from abc import ABC, abstractmethod
class BaseSender(ABC):
def send(self, message: str) -> None:
message = message.strip()
if message:
self.deliver(message)
@abstractmethod
def deliver(self, message: str) -> None: ...
class TerminalSender(BaseSender):
def deliver(self, message: str) -> None:
print(message)
TerminalSender().send(" 完成 ") prints “完成” (complete). It inherits the base class’s implementation of send. If a subclass omits deliver, Python allows the class definition but raises TypeError when you try to instantiate it. This is the runtime constraint provided by ABC together with @abstractmethod.5
The two approaches can coexist. Keep Sender on the notify parameter and you can pass the TerminalSender() above because it inherits a compatible send. Classes that want to reuse the cleanup step can inherit BaseSender, while the original RecordingSender continues to work as before.
Does dependency injection require a decorator? What does FastAPI’s Depends do?
The earlier notify(recording) call already performed manual injection. When a framework is the caller, the question becomes how to tell it where to obtain an argument. I wrote the following route in a FastAPI project. Here is just the signature.6
@router.post("/config_api")
async def config_api(request: Request, db: Session = Depends(get_db)):
...
These lines take effect at different times. At function definition time, the @router.post("/config_api") decorator registers the function as the route for that POST request. Depends(get_db) leaves an instruction on the parameter telling FastAPI to obtain the database session from get_db. Notice that what we pass is the function get_db. When a request arrives, FastAPI resolves the dependency and passes the resulting session to config_api as db. If a test calls this Python function directly, it must supply its own session to use it.7
Some libraries do express injection with decorators. Dependency Injector, for example, decorates a function with @inject, marks the required service with Provide[Container.service], then uses container.wire(...) to connect those markers to the container holding the service configuration.8 Returning to notifications, if the application entry point already knows which sender to use, notify(recording) expresses that choice directly. Add a Protocol to tell the team which objects are accepted. When several senders actually share part of the delivery process, move that code into a base class.
Footnotes
-
anchenhe9360. (n.d.). Python - python里有类似Java的接口(interface)吗? [Blog post]. CSDN. Original article. ↩
-
Python Software Foundation. (n.d.). Glossary. Python Documentation. “duck typing” entry. ↩
-
Levkivskyi, I., Lehtosalo, J., & Langa, Ł. (2017, March 5). PEP 544 – Protocols: Structural subtyping (static duck typing). Python Enhancement Proposals. Abstract, first paragraph. ↩
-
Sarfraz. (2009, December 16). What is the difference between an interface and abstract class? [Question]. Stack Overflow. Original question. ↩
-
Python Software Foundation. (n.d.). abc — Abstract Base Classes. Python 3.13 Documentation. abc.abstractmethod. ↩
-
CaiBorui. (2025, February 8). fetch 已经用了 JSON.stringify(),为什么 FastAPI 的 POST 接口还返回 422? [Blog post]. Project route and request body parsing code. ↩
-
FastAPI. (n.d.). Dependencies. FastAPI Tutorial. Simple usage. ↩
-
Dependency Injector. (n.d.). Wiring. Dependency Injector Documentation. Opening example and Decorator @inject. ↩