Performance: Class-based dependencies
MEDIUM IMPACT
This affects server response time and resource usage during request handling in FastAPI.
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 |