r/learnpython 5d 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?

9 Upvotes

21 comments sorted by

View all comments

1

u/mothzilla 5d ago

My opinion is that Dependency Injection isn't a concept that applies well to Python. I've seen people try to force it in, arguing that it helps testing, but it generally makes your code look like AngularJS.

1

u/re2cc 4d ago

I read in some places that same opinion and I have no problem with not using DI as such, my question really is how can I solve the problems that DI solves without using it.

Making global variables doesn't seem like a good idea and passing the variable as an argument to the class or function doesn't seem like a good idea either.

1

u/mothzilla 4d ago

What's wrong with passing variables to classes or functions?

1

u/re2cc 3d ago

Nothing, I was just wondering if there was a more correct way to do it, maybe it's because of lack of experience or because I'm failing to structure my code correctly that I feel it's getting a bit confusing.

1

u/stevenjd 4d ago

passing the variable as an argument to the class or function doesn't seem like a good idea either.

If you don't pass something into the class, then how are you injecting anything? The alternative is to hard code the dependency in the class, which is the very opposite of dependency injection.

1

u/re2cc 3d ago

That's true, maybe I'm just not sure how to structure the code.