From dec8c813192baa25ed0cd2329685dca899d87989 Mon Sep 17 00:00:00 2001 From: Matt Hartigan Date: Tue, 24 Feb 2026 22:32:37 +0000 Subject: [PATCH] fix: replace assert with raise FastAPIError in routing.py Three `assert isinstance(...)` guards in routing.py are used as runtime checks for required ASGI scope keys (fastapi_middleware_astack, fastapi_inner_astack). Under `python -O`, all assert statements are stripped, converting these diagnostic guards into silent AttributeError exceptions with no context. Replace with explicit `if not isinstance(...): raise FastAPIError(...)` to preserve the error messages regardless of Python optimization level. Affects: - get_request_handler() HTTP middleware stack check (line 349) - get_request_handler() HTTP dependency stack check (line 418) - get_websocket_app() WebSocket dependency stack check (line 514) --- fastapi/routing.py | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/fastapi/routing.py b/fastapi/routing.py index d17650a627..bd8717e119 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -346,9 +346,10 @@ def get_request_handler( async def app(request: Request) -> Response: response: Response | None = None file_stack = request.scope.get("fastapi_middleware_astack") - assert isinstance(file_stack, AsyncExitStack), ( - "fastapi_middleware_astack not found in request scope" - ) + if not isinstance(file_stack, AsyncExitStack): + raise FastAPIError( + "fastapi_middleware_astack not found in request scope" + ) # Extract endpoint context for error messages endpoint_ctx = ( @@ -415,9 +416,10 @@ def get_request_handler( # Solve dependencies and run path operation function, auto-closing dependencies errors: list[Any] = [] async_exit_stack = request.scope.get("fastapi_inner_astack") - assert isinstance(async_exit_stack, AsyncExitStack), ( - "fastapi_inner_astack not found in request scope" - ) + if not isinstance(async_exit_stack, AsyncExitStack): + raise FastAPIError( + "fastapi_inner_astack not found in request scope" + ) solved_result = await solve_dependencies( request=request, dependant=dependant, @@ -511,9 +513,10 @@ def get_websocket_app( mount_path = websocket.scope.get("root_path", "").rstrip("/") endpoint_ctx["path"] = f"WS {mount_path}{dependant.path}" async_exit_stack = websocket.scope.get("fastapi_inner_astack") - assert isinstance(async_exit_stack, AsyncExitStack), ( - "fastapi_inner_astack not found in request scope" - ) + if not isinstance(async_exit_stack, AsyncExitStack): + raise FastAPIError( + "fastapi_inner_astack not found in request scope" + ) solved_result = await solve_dependencies( request=websocket, dependant=dependant,