Junior — Middle
Have you ever used the Dependency Injector library for managing dependencies in Python projects?
sobes.tech AI
Answer from AI
Yes, the Dependency Injector library in Python is used for managing dependencies and injecting them into application components. It helps organize code, making it more modular and testable.
Example of usage:
from dependency_injector import containers, providers
class Service:
def do_something(self):
return "Service is working"
class Client:
def __init__(self, service: Service):
self.service = service
def run(self):
print(self.service.do_something())
class Container(containers.DeclarativeContainer):
service = providers.Singleton(Service)
client = providers.Factory(Client, service=service)
container = Container()
client = container.client()
client.run() # Will output: Service is working
This approach simplifies replacing implementations and facilitates testing, as dependencies can be substituted.