Skip to content

Commit 656db47

Browse files
committed
serializers: improve serialization time by caching fields items
1 parent 91bcd18 commit 656db47

File tree

1 file changed

+8
-3
lines changed

1 file changed

+8
-3
lines changed

src/graceful/serializers.py

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,11 @@ class CatSerializer(BaseSerializer):
8484
#: like defaultdict, SimpleNamespace or database model class.
8585
instance_factory = dict
8686

87+
def __init__(self):
88+
# perf: create cached list to save some processing
89+
# time during serialization and deserialization
90+
self._fields_items = list(self.fields.items())
91+
8792
@property
8893
def fields(self):
8994
"""Return dictionary of field definition objects of this serializer."""
@@ -112,7 +117,7 @@ def to_representation(self, instance):
112117
# inside of resource classes.
113118
representation = {}
114119

115-
for name, field in self.fields.items():
120+
for name, field in self._fields_items:
116121
# note: fields do not know their names in source representation
117122
# but may know what attribute they target from instance
118123
attribute = field.read_instance(instance, field.source or name)
@@ -174,7 +179,7 @@ def from_representation(self, representation, partial=False):
174179
representation, partial
175180
)
176181

177-
for name, field in self.fields.items():
182+
for name, field in self._fields_items:
178183
if name not in representation:
179184
continue
180185

@@ -230,7 +235,7 @@ def _validate_representation(self, representation, partial=False):
230235
failed validation.
231236
"""
232237
missing = [
233-
name for name, field in self.fields.items()
238+
name for name, field in self._fields_items
234239
if all((
235240
not partial,
236241
name not in representation,

0 commit comments

Comments
 (0)