FAST002 + B008 when using DI with FastAPI and Ruff
Closed this issue · 6 comments
Hi,
I am new to dependency_injector.
I am trying to use the FastAPI example code and ruff configured like so:
[tool.ruff.lint]
select = ["ALL"]
ignore = [
"FIX", # ignore TODOs
"TD", # ignore TODOs syntax
"D104", # Missing docstring in public package (__init__.py)
"D203", # 1 blank line required before class docstring, incomp. with D211
"D213", # multi-line-summary-second-line D212
# ruff warning, don't format these, conflicts with linter
"COM812", # missing-trailing-comma
"ISC001", # single-line-implicit-string-concatenation
]
I am getting B008 and FAST002
FastAPI dependency without `Annotated`
Do not perform function call `Depends` in argument defaults; instead, perform the call within the function, or read the default from a module-level singleton variable
Note: I cannot reproduce the FAST002 on the dependency_injector FastAPI basic example, just the B008 shows up.
Anyway, I tried doing this
"""FastAPI widh dependency_injector example."""
from typing import Annotated
from dependency_injector import containers, providers
from dependency_injector.wiring import Provide, inject
from fastapi import Depends, FastAPI, Response, status
class Service:
"""A mock service."""
async def process(self) -> str:
"""Return 'OK'."""
return "OK"
class Container(containers.DeclarativeContainer):
"""Container providing the mock Service."""
service = providers.Factory(Service)
app = FastAPI()
@app.api_route("/")
@inject
async def index(
response: Response,
service: Annotated[Service, Depends(Provide[Container.service])]
) -> dict[str, str]:
"""Verify that the injection works."""
result = await service.process()
response.status_code = status.HTTP_200_OK
return {"result": result}
container = Container()
container.wire(modules=[__name__])
Now ruff is happy, but DI breaks.
AttributeError: 'Provide' object has no attribute 'process'
I tried other variations, but nothing worked.
Is there a way to write this so ruff and mypy are happy, and DI continues to work?
Thank you
Hello. We've merged #721 just recently and haven't had a release yet, as it needs some docs and examples to be updated. I'll work on it this weekend, so stay tuned.
Oh, awesome. Sorry for the dupe
Woop 🎉
I will. I'm stuck setting up conftest for sqlalchemy async stuff, keeps closing the connection unexpectedly. Once i'm done with that, i will throw those Depends() calls out and test.
Tested it, it works great. Thank you.