Kink: Dependency Injection

0.9.0 · active · verified Fri Apr 17

Kink is a lightweight dependency injection (DI) library for Python, offering a straightforward way to manage and inject services and dependencies. It supports constructor, method, and property injection, leveraging Python's type hints for automatic resolution. The library is actively maintained, with new versions typically released every few months, ensuring compatibility with recent Python versions and addressing community feedback.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up a service with a dependency (a string prefix) using Kink's global `di` container and the `@inject` decorator for automatic dependency resolution. The `MyService` class requires a `message_prefix` which Kink resolves from the `di[str]` registration. The `run_application` function then receives an instance of `MyService`.

from kink import di, inject

class MyService:
    def __init__(self, message_prefix: str):
        self.message_prefix = message_prefix

    def get_greeting(self, name: str) -> str:
        return f"{self.message_prefix}, {name}!"

@inject
def run_application(service: MyService):
    print(service.get_greeting("World"))


# Configure the Dependency Injection container
di[str] = "Hello"
di[MyService] = MyService # Kink automatically resolves 'message_prefix' from di[str]

# Run the application, Kink injects MyService
run_application()

view raw JSON →