pip install python-injection
- Automatic dependency resolution based on type hints.
- Support for multiple dependency lifetimes:
transient
,singleton
,constant
, andscoped
. - Works seamlessly in both
async
andsync
environments. - Separation of dependency sets using modules.
- Runtime switching between different sets of dependencies.
- Centralized setup logic using entrypoints.
- Built-in type annotation for easy integration with
FastAPI
. - Lazy dependency resolution for optimized performance.
- Easy to use
- No impact on class and function definitions
- No tedious configuration
Simply apply the decorators and the package takes care of the rest.
from injection import injectable, inject, singleton
@singleton
class Printer:
def __init__(self):
self.history = []
def print(self, message: str):
self.history.append(message)
print(message)
@injectable
class Service:
def __init__(self, printer: Printer):
self.printer = printer
def hello(self):
self.printer.print("Hello world!")
@inject
def main(service: Service):
service.hello()
if __name__ == "__main__":
main()
⚠️ The package isn't threadsafe, for better performance in single-threaded applications and those usingasyncio
. So remember to usethreading.Lock
if you're writing a multithreaded program.