pip install python-injection- Automatic dependency resolution based on type hints.
- Support for multiple dependency lifetimes: transient,singleton,constant, andscoped.
- Works seamlessly in both asyncandsyncenvironments.
- 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 by default, for better performance in single-threaded applications and those usingasyncio.Non-threadsafe functions are those that resolve dependencies or define scopes. They all come with an optional parameter
threadsafe.You can set
PYTHON_INJECTION_THREADSAFE=1in environment variables to make the package fully threadsafe. The environment variable is resolved at the Python module level, so be careful if the variable is defined dynamically.