Skip to content

FAST002 + B008 when using DI with FastAPI and Ruff #850

Closed
@TojikCZ

Description

@TojikCZ

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions