Skip to content

Commit

Permalink
⚡ Update create_cloned_field to use a global cache and improve star…
Browse files Browse the repository at this point in the history
…tup performance (#4645)

Co-authored-by: Sebastián Ramírez <tiangolo@gmail.com>
Co-authored-by: Huon Wilson <wilson.huon@gmail.com>
  • Loading branch information
3 people committed Jun 3, 2023
1 parent d057294 commit 27618aa
Showing 1 changed file with 22 additions and 4 deletions.
26 changes: 22 additions & 4 deletions fastapi/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,18 @@
import warnings
from dataclasses import is_dataclass
from enum import Enum
from typing import TYPE_CHECKING, Any, Dict, Optional, Set, Type, Union, cast
from typing import (
TYPE_CHECKING,
Any,
Dict,
MutableMapping,
Optional,
Set,
Type,
Union,
cast,
)
from weakref import WeakKeyDictionary

import fastapi
from fastapi.datastructures import DefaultPlaceholder, DefaultType
Expand All @@ -16,6 +27,11 @@
if TYPE_CHECKING: # pragma: nocover
from .routing import APIRoute

# Cache for `create_cloned_field`
_CLONED_TYPES_CACHE: MutableMapping[
Type[BaseModel], Type[BaseModel]
] = WeakKeyDictionary()


def is_body_allowed_for_status_code(status_code: Union[int, str, None]) -> bool:
if status_code is None:
Expand Down Expand Up @@ -98,11 +114,13 @@ def create_response_field(
def create_cloned_field(
field: ModelField,
*,
cloned_types: Optional[Dict[Type[BaseModel], Type[BaseModel]]] = None,
cloned_types: Optional[MutableMapping[Type[BaseModel], Type[BaseModel]]] = None,
) -> ModelField:
# _cloned_types has already cloned types, to support recursive models
# cloned_types caches already cloned types to support recursive models and improve
# performance by avoiding unecessary cloning
if cloned_types is None:
cloned_types = {}
cloned_types = _CLONED_TYPES_CACHE

original_type = field.type_
if is_dataclass(original_type) and hasattr(original_type, "__pydantic_model__"):
original_type = original_type.__pydantic_model__
Expand Down

0 comments on commit 27618aa

Please sign in to comment.