From 3c1dd7fdf28663e42bdd20811179ca587bd97344 Mon Sep 17 00:00:00 2001 From: rajratanm Date: Tue, 24 Mar 2026 17:31:26 +0530 Subject: [PATCH] Fix routing type-check failures in pre-commit. Normalize request handler typing in routing utils and explicitly type APIRoute.response_field to satisfy mypy and ty hooks. Made-with: Cursor --- fastapi/routing_routes.py | 3 ++- fastapi/routing_utils.py | 14 ++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/fastapi/routing_routes.py b/fastapi/routing_routes.py index 61035d77c1..02b0bdf84a 100644 --- a/fastapi/routing_routes.py +++ b/fastapi/routing_routes.py @@ -163,6 +163,7 @@ class APIRoute(routing.Route): if isinstance(status_code, IntEnum): status_code = int(status_code) self.status_code = status_code + self.response_field: ModelField | None if self.response_model: assert is_body_allowed_for_status_code(status_code), ( f"Status code {status_code} must not have a response body" @@ -174,7 +175,7 @@ class APIRoute(routing.Route): mode="serialization", ) else: - self.response_field = None # type: ignore + self.response_field = None if self.stream_item_type: stream_item_name = "StreamItem_" + self.unique_id self.stream_item_field: ModelField | None = create_model_field( diff --git a/fastapi/routing_utils.py b/fastapi/routing_utils.py index 6baf2226b9..5857258c95 100644 --- a/fastapi/routing_utils.py +++ b/fastapi/routing_utils.py @@ -15,7 +15,7 @@ from contextlib import ( AsyncExitStack, asynccontextmanager, ) -from typing import Any, TypeVar +from typing import Any, TypeVar, cast from fastapi._compat import ModelField from fastapi.dependencies.models import Dependant @@ -40,9 +40,15 @@ _T = TypeVar("_T") def request_response( func: Callable[[Request], Awaitable[Response] | Response], ) -> ASGIApp: - f: Callable[[Request], Awaitable[Response]] = ( - func if is_async_callable(func) else functools.partial(run_in_threadpool, func) # type: ignore[call-arg] - ) + if is_async_callable(func): + f: Callable[[Request], Awaitable[Response]] = cast( + Callable[[Request], Awaitable[Response]], func + ) + else: + sync_func = cast(Callable[[Request], Response], func) + + async def f(request: Request) -> Response: + return await run_in_threadpool(sync_func, request) async def app(scope: Scope, receive: Receive, send: Send) -> None: request = Request(scope, receive, send)