Problem Statement
How do you apply dependency injection (DI) in Python without a heavy framework?
Explanation
Pass interfaces or callables into constructors or function parameters. Build the object graph at startup in a small composition root. Use factories for resources like clients or repositories.
This keeps modules decoupled and testable. In tests, swap real dependencies for fakes by passing different constructors or using monkeypatch.
Code Solution
SolutionRead Only
class Service:
def __init__(self, repo): self.repo=repo
def build():
repo = SqlRepo(url)
return Service(repo)