1- import functools
21import inspect
32
43from sqlalchemy import inspect as sql_inspect
54
5+ # Cache for get_serializable_keys results,
6+ # keyed by (class, serializable_keys_tuple, auto_serialize_properties)
7+ _serializable_keys_cache : dict [tuple [type , tuple | None , bool ], set [str ]] = {}
8+
9+
10+ def _get_cache_key (model_instance ) -> tuple [type , tuple | None , bool ]:
11+ """Generate cache key from model instance configuration.
12+
13+ :param model_instance: Model instance to extract cache key from
14+ :return: Tuple of (class, serializable_keys_tuple, auto_serialize_properties)
15+ """
16+ cls = model_instance .__class__
17+ serializable_keys = (
18+ tuple (model_instance .serializable_keys ) if model_instance .serializable_keys else None
19+ )
20+ auto_serialize_properties = bool (model_instance .auto_serialize_properties )
21+ return (cls , serializable_keys , auto_serialize_properties )
22+
623
724def get_sql_field_names (model_instance ) -> set [str ]:
825 """:return: set of sql fields names
@@ -18,18 +35,27 @@ def get_property_field_names(model_instance) -> set[str]:
1835 return {name for name , member in inspect .getmembers (cls ) if isinstance (member , property )}
1936
2037
21- @functools .lru_cache
2238def get_serializable_keys (model_instance ) -> set [str ]:
2339 """:return: set of keys available for serialization
2440 :raise: sqlalchemy.exc.NoInspectionAvailable if model_instance is not an sqlalchemy mapper
41+
42+ Results are cached by class and configuration
43+ (serializable_keys, auto_serialize_properties)
44+ rather than by instance, improving cache efficiency
45+ for collections of the same model type.
2546 """
47+ cache_key = _get_cache_key (model_instance )
48+
49+ if cache_key in _serializable_keys_cache :
50+ return _serializable_keys_cache [cache_key ]
51+
2652 if model_instance .serializable_keys :
2753 result = set (model_instance .serializable_keys )
28-
2954 else :
3055 result = get_sql_field_names (model_instance )
3156
3257 if model_instance .auto_serialize_properties :
3358 result .update (get_property_field_names (model_instance ))
3459
60+ _serializable_keys_cache [cache_key ] = result
3561 return result
0 commit comments