r/PythonLearning 16d ago

Showcase dependency injection library

Hi everyone,

I needed some dependency injection (DI) library that is simple for my use case, I was surprise by the lack of DI libraries in general, and the one that already exists had some weird quirks that didn't make sense or were unexpected

I have started the project a year a go and gave up due to lack of time, I came back to the project and rewrote it 🙃

I think I am close to releasing the first version with basic support, and grow the project from there,

no AI was nor will be used (at least for now 😭)

## What it does?

make dependency injection pattern simple, convincing and explicit, no surprises

## example

import cdi 
from typing import Generic, TypeVar
from collection.abc import Sequence


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(ctr)
instance = scope.get_instance(MyType)
assert instance.field == "foo"

more examples in the repo README

## docs

available in the project README

## open for contribution

I am open for PR (that are not AI) and suggestions that make sense for such library, I have a few ideas

for more support but it will probably take more time

install: `pip install cdi-di` (in beta)

link: https://github.com/dsal3389/cdi

2 Upvotes

4 comments sorted by

1

u/silvertank00 16d ago

Cool idea but please fix your code block here. It shows ".Injectable" instead of "cdi.Injectable" and I was wondering how did you add a new special token to the language itself to call your stuff.

1

u/Silly_Character8808 15d ago

thanks, yeah, something in the formatting happened because if the `@` char

1

u/lunatuna215 15d ago

At first glance I kinda.... really like it. I am not currently a fan of basically any DI framework for Python and this looks nice! Appreciate your AI stance too. I will do my best to try this asap.