Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FAST002 rule produces false positives and incorrect suggestions #15043

Open
MarkusSintonen opened this issue Dec 18, 2024 · 1 comment
Open
Labels
bug Something isn't working fixes Related to suggested fixes for violations

Comments

@MarkusSintonen
Copy link

MarkusSintonen commented Dec 18, 2024

Ruff (0.8.3) FAST002 produces false positives and suggests incorrect Annotated format with FastAPI params having default values. Following example can not be converted into the Annotated format as FastAPI does not support this format with params having default values. Also --unsafe-fixes fixes it to the format the FastAPI wont accept.

Ruff FAST002 violation:

def test_fast002_bug():
    from fastapi import FastAPI, Query
    app = FastAPI()

    @app.get("/test")
    def handler(echo: str = Query("")):  # FAST002 FastAPI dependency without `Annotated`
        return echo

But that is not compatible with FastAPI. It fails deeply with an AssertionError:

def test_fast002_bug():
    from typing import Annotated
    from fastapi import FastAPI, Query
    app = FastAPI()

    # AssertionError: `Query` default value cannot be set in `Annotated` for 'echo'. Set the default value with `=` instead.
    @app.get("/test")
    def handler(echo: Annotated[str, Query("")]):
        return echo

Used FastAPI 0.115.5.

The rule is pretty nice otherwise so thanks for it! Hopefully we get it fixed.

@MichaReiser
Copy link
Member

Thanks for opening the issue. I think this is a true positive, but the fix is incorrect. The Query default value cannot be used inside Annotated according to FastAPI's documentation. Instead, a regular default value should be used. So the proper fix for your example is to rewrite it to

def test_fast002_bug():
    from typing import Annotated
    from fastapi import FastAPI, Query
    app = FastAPI()

    # AssertionError: `Query` default value cannot be set in `Annotated` for 'echo'. Set the default value with `=` instead.
    @app.get("/test")
    def handler(echo: Annotated[str, Query()] = ""):
        return echo

@MichaReiser MichaReiser added bug Something isn't working fixes Related to suggested fixes for violations labels Dec 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working fixes Related to suggested fixes for violations
Projects
None yet
Development

No branches or pull requests

2 participants