Simplifying Python dependency injection.
Project details
CDI is a powerful yet straightforward dependency injection library for Python. It enables developers to create and manage dependencies easily, ensuring code remains clean and maintainable. With features like forward reference resolution and support for circular dependencies, CDI strikes the right balance between simplicity and functionality.
cdi is a powerful Python dependency injection library designed for simplicity and ease of use. It streamlines the process of dependency management, allowing developers to focus on building features without the hassle of complex dependency configuration.
The library embodies the principle that explicit is better than implicit. It encourages clear type definitions without sacrificing readability or usability, making it easier for developers to define and manage dependencies.
Here's how to define a simple injectable class:
import cdi
# Create a container for dependency registration
ctr = cdi.Container()
# Register a factory function for integers
@cdi.Injectable(ctr)
def get_int() -> int:
return 100
# Register a class Foo that will use the integer
@cdi.Injectable(ctr)
class Foo:
def __init__(self, number: int) -> None:
self.number = number
# Create a scope to resolve dependencies
scope = cdi.Scope(cdi)
instance = scope.get_instance(Foo)
assert instance.number == 100
Advanced usage, including generics and complex object relationships, can also be managed with ease:
from typing import Generic, TypeVar
T = TypeVar('T')
ctr = cdi.Container()
class MyBase(Generic[T]):
def __init__(self, field: T) -> None:
self.field = field
@cdi.Injectable(ctr)
class MyType(MyBase[str]): pass
@cdi.Injectable(ctr)
def name_generator() -> str:
return "foo"
scope = cdi.Scope(__name__, container=ctr)
instance = scope.get_instance(MyType)
assert instance.field == "foo"
While cdi does not have an explicit async interface, it supports async code seamlessly. It does not yield control back but ensures it works efficiently with multiple asyncio executors, thanks to a thread-safe design using internal locks.
cdi provides a robust and user-friendly framework for dependency injection in Python applications. It simplifies dependency management, enhances code clarity, and facilitates scalable architecture without the common pitfalls of overly complex setups. This library is ideal for developers looking for an efficient solution to manage dependencies cleanly and effectively.
Comments
0Start the conversation
Share the first comment.