[`ruff`] Reduce FastAPI false positives in `unused-async` (`RUF029`) (#12938)

This commit is contained in:
TomerBin 2024-08-17 17:25:14 +03:00 committed by GitHub
parent 96802d6a7f
commit 52ba94191a
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 0 deletions

View File

@ -78,3 +78,13 @@ async def test():
async def test() -> str: async def test() -> str:
vals = [str(val) for val in await async_func(1)] vals = [str(val) for val in await async_func(1)]
return ",".join(vals) return ",".join(vals)
from fastapi import FastAPI
app = FastAPI()
@app.post("/count")
async def fastapi_route(): # Ok: FastApi routes can be async without actually using await
return 1

View File

@ -4,8 +4,10 @@ use ruff_python_ast::identifier::Identifier;
use ruff_python_ast::visitor::source_order; use ruff_python_ast::visitor::source_order;
use ruff_python_ast::{self as ast, AnyNodeRef, Expr, Stmt}; use ruff_python_ast::{self as ast, AnyNodeRef, Expr, Stmt};
use ruff_python_semantic::analyze::function_type::is_stub; use ruff_python_semantic::analyze::function_type::is_stub;
use ruff_python_semantic::Modules;
use crate::checkers::ast::Checker; use crate::checkers::ast::Checker;
use crate::rules::fastapi::rules::is_fastapi_route;
/// ## What it does /// ## What it does
/// Checks for functions declared `async` that do not await or otherwise use features requiring the /// Checks for functions declared `async` that do not await or otherwise use features requiring the
@ -173,6 +175,12 @@ pub(crate) fn unused_async(
return; return;
} }
if checker.semantic().seen_module(Modules::FASTAPI)
&& is_fastapi_route(function_def, checker.semantic())
{
return;
}
let found_await_or_async = { let found_await_or_async = {
let mut visitor = AsyncExprVisitor::default(); let mut visitor = AsyncExprVisitor::default();
source_order::walk_body(&mut visitor, body); source_order::walk_body(&mut visitor, body);