From 423cf421f94173cf8bd513eaa0c3b9e493f445b4 Mon Sep 17 00:00:00 2001 From: saif Date: Mon, 14 Oct 2024 12:48:04 +0300 Subject: [PATCH 1/2] refactor: Refactor loop to list comprehension for performance optimization --- fastapi/encoders.py | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index 451ea0760..bb96b162a 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -297,22 +297,20 @@ def jsonable_encoder( encoded_dict[encoded_key] = encoded_value return encoded_dict if isinstance(obj, (list, set, frozenset, GeneratorType, tuple, deque)): - encoded_list = [] - for item in obj: - encoded_list.append( - jsonable_encoder( - item, - include=include, - exclude=exclude, - by_alias=by_alias, - exclude_unset=exclude_unset, - exclude_defaults=exclude_defaults, - exclude_none=exclude_none, - custom_encoder=custom_encoder, - sqlalchemy_safe=sqlalchemy_safe, - ) + return [ + jsonable_encoder( + item, + include=include, + exclude=exclude, + by_alias=by_alias, + exclude_unset=exclude_unset, + exclude_defaults=exclude_defaults, + exclude_none=exclude_none, + custom_encoder=custom_encoder, + sqlalchemy_safe=sqlalchemy_safe, ) - return encoded_list + for item in obj + ] if type(obj) in ENCODERS_BY_TYPE: return ENCODERS_BY_TYPE[type(obj)](obj) From ef0dcd2f11ac354be03551f2d2670a57f908ff24 Mon Sep 17 00:00:00 2001 From: saif Date: Mon, 14 Oct 2024 13:14:50 +0300 Subject: [PATCH 2/2] refactor: Initialize 'errors' list and append 'e' to it in one line --- fastapi/encoders.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/fastapi/encoders.py b/fastapi/encoders.py index bb96b162a..cc0d26a28 100644 --- a/fastapi/encoders.py +++ b/fastapi/encoders.py @@ -321,8 +321,7 @@ def jsonable_encoder( try: data = dict(obj) except Exception as e: - errors: List[Exception] = [] - errors.append(e) + errors: List[Exception] = [e] try: data = vars(obj) except Exception as e: