From 0b567f86b2bdbe7af04e176f4e4d08087c9b3432 Mon Sep 17 00:00:00 2001 From: kim Date: Tue, 8 Jul 2025 14:42:43 +0900 Subject: [PATCH] perf: optimize OpenAPI response class status code detection Add caching mechanism for default_status_code attribute to avoid repeated signature inspection, improving schema generation performance. --- fastapi/openapi/utils.py | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/fastapi/openapi/utils.py b/fastapi/openapi/utils.py index 808646cc2..f2a84bf51 100644 --- a/fastapi/openapi/utils.py +++ b/fastapi/openapi/utils.py @@ -338,16 +338,16 @@ def get_openapi_path( if route.status_code is not None: status_code = str(route.status_code) else: - # It would probably make more sense for all response classes to have an - # explicit default status_code, and to extract it from them, instead of - # doing this inspection tricks, that would probably be in the future - # TODO: probably make status_code a default class attribute for all - # responses in Starlette - response_signature = inspect.signature(current_response_class.__init__) - status_code_param = response_signature.parameters.get("status_code") - if status_code_param is not None: - if isinstance(status_code_param.default, int): - status_code = str(status_code_param.default) + # Use cached attribute if available, otherwise fall back to inspection + # This improves performance by avoiding repeated signature inspection + if hasattr(current_response_class, "default_status_code"): + status_code = str(current_response_class.default_status_code) + else: + response_signature = inspect.signature(current_response_class.__init__) + status_code_param = response_signature.parameters.get("status_code") + if status_code_param is not None: + if isinstance(status_code_param.default, int): + status_code = str(status_code_param.default) operation.setdefault("responses", {}).setdefault(status_code, {})[ "description" ] = route.response_description