Skip to content

100nm/python-injection

Repository files navigation

python-injection

CI PyPI - Version PyPI - Downloads Ruff

Installation

⚠️ Requires Python 3.12 or higher

pip install python-injection

Features

  • Automatic dependency resolution based on type hints.
  • Support for multiple dependency lifetimes: transient, singleton, constant, and scoped.
  • Works seamlessly in both async and sync 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.

Motivations

  1. Easy to use
  2. No impact on class and function definitions
  3. No tedious configuration

Quick start

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()

Resources

⚠️ The package isn't threadsafe, for better performance in single-threaded applications and those using asyncio. So remember to use threading.Lock if you're writing a multithreaded program.