Picobox Dependency Injection

4.0.0 · active · verified Wed Apr 15

Picobox is an opinionated, lightweight (around 500 LOC) dependency injection framework for Python, designed to be clean and pragmatic. It focuses on explicit demands without complex graphs, implicit injections, or XML configurations. The current version is 4.0.0, and it maintains an active development with regular major and minor releases, including support for new Python versions and deprecations of older ones.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates defining a `Box`, adding both value and factory dependencies with scoping, and then using the `@picobox.pass_` decorator to inject these dependencies into a function. The `picobox.push()` function is used as a context manager to activate the box for the current scope.

import picobox

class MyService:
    def __init__(self, config_value: int):
        self.config_value = config_value

    def do_work(self) -> str:
        return f"Working with config: {self.config_value}"

# 1. Create a Box instance
box = picobox.Box()

# 2. Put dependencies into the box
# 'my_config' is a simple value
box.put('my_config', 123)

# 'my_service' is a factory, instantiated once per injection or scope
box.put('my_service', factory=MyService, scope=picobox.singleton, depends=['my_config'])

# 3. Use picobox.push to make the box active (often as a context manager)
with picobox.push(box):
    # 4. Define a function that needs dependencies, using @picobox.pass_
    @picobox.pass_('my_service')
    @picobox.pass_('my_config', as_='cfg_val')
    def run_application(my_service: MyService, cfg_val: int):
        print(f"Retrieved config value: {cfg_val}")
        print(my_service.do_work())

    run_application()

view raw JSON →