dependency injection #176990
Replies: 9 comments
-
|
hope it will help Dependency Injection (DI) is a way to give a class the things it needs (dependencies) instead of creating them inside the class. Without Dependency Injection 🔴 Problem: UserService is tightly linked to Database — hard to test or replace. With Dependency Injection ✅ Now you can pass any database you want: user_service = UserService(Database()) When to Use For testing (mock dependencies easily) To make code flexible and reusable In frameworks like Flask or FastAPI In short: |
Beta Was this translation helpful? Give feedback.
-
|
🕒 Discussion Activity Reminder 🕒 This Discussion has been labeled as dormant by an automated system for having no activity in the last 60 days. Please consider one the following actions: 1️⃣ Close as Out of Date: If the topic is no longer relevant, close the Discussion as 2️⃣ Provide More Information: Share additional details or context — or let the community know if you've found a solution on your own. 3️⃣ Mark a Reply as Answer: If your question has been answered by a reply, mark the most helpful reply as the solution. Note: This dormant notification will only apply to Discussions with the Thank you for helping bring this Discussion to a resolution! 💬 |
Beta Was this translation helpful? Give feedback.
-
What is Dependency Injection (DI)?Dependency Injection is a design pattern where an object receives its dependencies from the outside instead of creating them internally. In simple terms:
This makes code loosely coupled, testable, and easy to maintain. Without Dependency Injection (tight coupling)class OrderService:
def __init__(self):
self.db = Database() # hard dependency
def create_order(self, order):
self.db.save(order)Problems:
With Dependency Injection (loose coupling)class OrderService:
def __init__(self, db):
self.db = db # dependency injected
def create_order(self, order):
self.db.save(order)Usage: db = Database()
service = OrderService(db)Benefits:
Common Scenarios to Use Dependency Injection in Python1. Unit TestingInject mock objects instead of real ones. class MockDatabase:
def save(self, data):
print("Mock save")
service = OrderService(MockDatabase())2. Swapping ImplementationsExample: switch between different databases. class MySQLDatabase:
def save(self, data): ...
class MongoDatabase:
def save(self, data): ...service = OrderService(MySQLDatabase())
# or
service = OrderService(MongoDatabase())3. Configuration-Based BehaviorInject different services based on environment. if ENV == "prod":
db = MySQLDatabase()
else:
db = SQLiteDatabase()4. Web Frameworks (FastAPI, Flask, Django)FastAPI has built-in DI: from fastapi import Depends
def get_db():
return Database()
@app.get("/items")
def read_items(db=Depends(get_db)):
return db.fetch_items()5. Following SOLID PrinciplesDI supports the Dependency Inversion Principle:
Ways to Implement Dependency Injection in Python
When NOT to Use Dependency Injection
|
Beta Was this translation helpful? Give feedback.
-
|
🕒 Discussion Activity Reminder 🕒 This Discussion has been labeled as dormant by an automated system for having no activity in the last 60 days. Please consider one the following actions: 1️⃣ Close as Out of Date: If the topic is no longer relevant, close the Discussion as 2️⃣ Provide More Information: Share additional details or context — or let the community know if you've found a solution on your own. 3️⃣ Mark a Reply as Answer: If your question has been answered by a reply, mark the most helpful reply as the solution. Note: This dormant notification will only apply to Discussions with the Thank you for helping bring this Discussion to a resolution! 💬 |
Beta Was this translation helpful? Give feedback.
-
|
Dependency Injection (DI) = instead of a class creating what it needs inside itself, Simple example: class Database:
def save(self, data):
print("saved")
class UserService:
def __init__(self, db): # dependency injected
self.db = db
def create_user(self, name):
self.db.save(name)
db = Database()
service = UserService(db)
service.create_user("Ali")When to use DI in Python:
Rule of thumb: |
Beta Was this translation helpful? Give feedback.
-
|
Dependency Injection, or DI, is a design pattern where a class or function receives the objects it depends on from the outside instead of creating them internally. In simple terms, instead of a class doing self.db = Database() inside its own code, you pass the database object into it. This makes the code more flexible, easier to test, and less tightly coupled. In Python, you usually do not need a complex framework for DI. The most common and Pythonic way is simply passing dependencies through the constructor or function parameters. Here is a simple example: Now UserService does not care how repo is created. You can pass a real database repository in production, and a fake or mock repository in tests. Common scenarios where DI is useful in Python: Testing Switching environments Reusable services Larger applications If you are using frameworks like FastAPI, dependency injection is built in using Depends(), which is commonly used for database sessions, authentication, and shared logic. As a general rule, if creating objects inside your classes makes testing difficult or swapping implementations painful, dependency injection is a good solution. |
Beta Was this translation helpful? Give feedback.
-
|
Dependency Injection (DI) means giving a class or function its dependencies from outside instead of creating them inside. This makes code loosely coupled, testable, and flexible.
|
Beta Was this translation helpful? Give feedback.
-
|
Great examples here already! For a modern Python approach (3.8+), I highly recommend using Instead of inheriting from a base abstract class (ABC), Protocols allow you to define the shape of the dependency you need. This decouples your service from the implementation details entirely. from typing import Protocol
class Database(Protocol):
def save(self, data: dict) -> None:
...
class UserService:
def __init__(self, db: Database):
self.db = db # Type checker ensures 'db' has a .save() method
# Now any class with a .save() method works, no inheritance required!
class PostgresDB: # Doesn't need to inherit from anything
def save(self, data: dict):
print("Saved to Postgres")
service = UserService(PostgresDB())This is often called Structural Subtyping (duck typing) and makes DI in Python much more flexible compared to rigid Java/C# style inheritance hierarchies. |
Beta Was this translation helpful? Give feedback.
-
|
here minimal concerte python examples of dependency injection using plain classes and constructor injection from abc import ABC, abstractmethod Abstraction (interface)class EmailClient(ABC): One concrete implementationclass SmtpEmailClient(EmailClient): Another implementation for testsclass InMemoryEmailClient(EmailClient): Service that depends on the abstraction, not a concrete typeclass UserService: Composition root / manual DI "container"def create_user_service_for_prod() -> UserService: def create_user_service_for_tests() -> tuple[UserService, InMemoryEmailClient]: if name == "main": |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
Select Topic Area
Question
Body
wat is dependency injection. scenarios to use dependency injection in python
Beta Was this translation helpful? Give feedback.
All reactions