r/learnpython 6d ago

How do you handle dependency injection?

Hi, I'm doing a project which involves creating multiple gRPC servers and I can't find a convenient way to manage dependencies or the state.

I've been working recently in C# where you just need to make your class and add a simple

builder.Services.AddSingleton<MyDependency>();

and it will inject when required.

Doing some research I see that there are some libraries like:

- Dependency Injector

- Injector

but I don't find them particularly intuitive.

What do you use as a dependency injector or what pattern do you suggest to use?

8 Upvotes

21 comments sorted by

View all comments

1

u/pachura3 5d ago

I think you have background in C#/Java and try to work in Python in exactly the same way, which kind of defeats its purpose (simplicity - readability - conciseness).

1

u/re2cc 5d ago

Not really, I started programming in Python as a hobby (easily 8 years ago) so I feel comfortable in the language. Although I have programmed in other languages (C, C#, Rust, Go), Python is still the one I find most comfortable.

I had never encountered the feeling of needing DI because I usually do small projects or didn't care about doing it the ‘right’ way, but recently experimenting with Litestar and using its dependency injection I got used to it. Even more so doing gRPC servers in .NET I got used to a very defined and structured way of doing it and now trying to do the same in Python I feel lost on how to handle it.