Performance: Class-based dependencies
This affects server response time and resource usage during request handling in FastAPI.
Jump into concepts and practice - no test required
from fastapi import Depends from fastapi import FastAPI app = FastAPI() class DBSession: def __init__(self): self.db = create_db_session() def __enter__(self): return self.db def __exit__(self, exc_type, exc_val, exc_tb): self.db.close() def get_db(session: DBSession = Depends(DBSession)): with session as db: yield db @app.get("/items/") async def read_items(db=Depends(get_db)): return db.query(Item).all()
from fastapi import Depends from fastapi import FastAPI app = FastAPI() def get_db(): db = create_db_session() try: yield db finally: db.close() @app.get("/items/") async def read_items(db=Depends(get_db)): return db.query(Item).all()
| Pattern | Instance Creation | Setup/Teardown Calls | Memory Usage | Verdict |
|---|---|---|---|---|
| Function-based dependency | No instance, function call only | Setup/teardown logic repeated per call | Lower memory per request | [!] OK |
| Class-based dependency | One instance per request | Encapsulated setup/teardown in class | Slightly higher memory per request | [OK] Good |
from fastapi import FastAPI, Depends
app = FastAPI()
class Greeting:
def __init__(self, name: str = "Guest"):
self.name = name
def __call__(self):
return f"Hello, {self.name}!"
@app.get("/hello")
async def hello(greet: str = Depends(Greeting)):
return {"message": greet}class Counter:
def __init__(self):
self.count = 0
def increment(self):
self.count += 1
@app.get("/count")
async def get_count(counter: Counter = Depends(Counter)):
counter.increment()
return {"count": counter.count}class UserInfo:
def __init__(self, user_id: int):
self.user_id = user_id
def __call__(self):
return f"User ID is {self.user_id}"
@app.get("/user")
async def user(info: str = Depends(UserInfo)):
return {"info": info}user_id from query parameters.