From 78ea8a2107010629dd997baf3740fae438c41e3a Mon Sep 17 00:00:00 2001 From: Hiten Shah Date: Tue, 24 Mar 2026 12:56:25 -0700 Subject: [PATCH] refactor: Move type-only imports into TYPE_CHECKING blocks Move imports that are only used for type annotations into TYPE_CHECKING blocks to prevent unnecessary runtime imports and potential circular import issues. Changes: - fastapi/openapi/utils.py: Response - tests/test_dependency_contextmanager.py: StreamingResponse - tests/test_route_scope.py: APIRoute Detected via: ruff check . --select TC002 --- fastapi/openapi/utils.py | 6 ++++-- tests/test_dependency_contextmanager.py | 5 ++++- tests/test_route_scope.py | 5 ++++- 3 files changed, 12 insertions(+), 4 deletions(-) diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 8f1852b0cc..a501ca12bd 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -3,7 +3,7 @@ import http.client import inspect import warnings from collections.abc import Sequence -from typing import Any, Literal, cast +from typing import Any, Literal, cast, TYPE_CHECKING from fastapi import routing from fastapi._compat import ( @@ -27,7 +27,6 @@ from fastapi.exceptions import FastAPIDeprecationWarning from fastapi.openapi.constants import METHODS_WITH_BODY, REF_PREFIX from fastapi.openapi.models import OpenAPI from fastapi.params import Body, ParamTypes -from fastapi.responses import Response from fastapi.sse import _SSE_EVENT_SCHEMA from fastapi.types import ModelNameMap from fastapi.utils import ( @@ -39,6 +38,9 @@ from pydantic import BaseModel from starlette.responses import JSONResponse from starlette.routing import BaseRoute +if TYPE_CHECKING: + from fastapi.responses import Response + validation_error_definition = { "title": "ValidationError", "type": "object", diff --git a/tests/test_dependency_contextmanager.py b/tests/test_dependency_contextmanager.py index 5a89934741..b7c7a627b4 100644 --- a/tests/test_dependency_contextmanager.py +++ b/tests/test_dependency_contextmanager.py @@ -2,8 +2,11 @@ import json import pytest from fastapi import BackgroundTasks, Depends, FastAPI -from fastapi.responses import StreamingResponse from fastapi.testclient import TestClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from fastapi.responses import StreamingResponse app = FastAPI() state = { diff --git a/tests/test_route_scope.py b/tests/test_route_scope.py index 792ea66c3a..1e69f38cb1 100644 --- a/tests/test_route_scope.py +++ b/tests/test_route_scope.py @@ -1,7 +1,10 @@ import pytest from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect -from fastapi.routing import APIRoute, APIWebSocketRoute from fastapi.testclient import TestClient +from typing import TYPE_CHECKING + +if TYPE_CHECKING: + from fastapi.routing import APIRoute, APIWebSocketRoute app = FastAPI()