Sobes.tech
Junior — Middle

This question concerns your experience with implementing and using the Dependency Injection pattern. Could you tell us if you have encountered this approach in your projects?

sobes.tech AI

Answer from AI

Yes, in my Python projects, I have used the Dependency Injection (DI) pattern to improve code modularity and testability. DI allows dependencies of an object to be passed from outside rather than created inside, which makes component replacement easier and simplifies testing.

For example, instead of creating an instance of a service inside a class, I pass it through the constructor:

class EmailService:
    def send_email(self, to, subject, body):
        pass  # Email sending implementation

class UserRegistration:
    def __init__(self, email_service):
        self.email_service = email_service

    def register(self, user):
        # Registration logic
        self.email_service.send_email(user.email, "Welcome", "Thank you for registering")

# Usage
email_service = EmailService()
registration = UserRegistration(email_service)
registration.register(user)

In more complex projects, I used DI libraries such as injector or dependency-injector, which help manage dependencies centrally and automatically.