diff --git a/fastapi/routing.py b/fastapi/routing.py index ea82ab14a..54687ce8b 100644 --- a/fastapi/routing.py +++ b/fastapi/routing.py @@ -232,16 +232,16 @@ class _DefaultLifespan: return self -# Cache for endpoint context to avoid re-extracting on every request -_endpoint_context_cache: dict[int, EndpointContext] = {} +# Cache for endpoint context to avoid re-extracting on every request. +# Keyed on the function object itself (not id()) so that entries remain valid +# even if a function is garbage collected and its id is reused by a new object. +_endpoint_context_cache: dict[Callable[..., Any], EndpointContext] = {} def _extract_endpoint_context(func: Any) -> EndpointContext: """Extract endpoint context with caching to avoid repeated file I/O.""" - func_id = id(func) - - if func_id in _endpoint_context_cache: - return _endpoint_context_cache[func_id] + if func in _endpoint_context_cache: + return _endpoint_context_cache[func] try: ctx: EndpointContext = {} @@ -255,7 +255,7 @@ def _extract_endpoint_context(func: Any) -> EndpointContext: except Exception: ctx = EndpointContext() - _endpoint_context_cache[func_id] = ctx + _endpoint_context_cache[func] = ctx return ctx