Skip to content

Commit 8bc85c6

Browse files
committed
fix: use custom serializers for custom sequence values
1 parent 2009ddd commit 8bc85c6

File tree

2 files changed

+25
-4
lines changed

2 files changed

+25
-4
lines changed

aws_lambda_powertools/event_handler/openapi/encoders.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,7 @@ def jsonable_encoder( # noqa: PLR0911
130130
exclude_none=exclude_none,
131131
exclude_defaults=exclude_defaults,
132132
exclude_unset=exclude_unset,
133+
custom_serializer=custom_serializer,
133134
)
134135

135136
# Other types
@@ -209,7 +210,8 @@ def _dump_dict(
209210
210211
Parameters
211212
----------
212-
custom_serializer
213+
custom_serializer : Callable, optional
214+
A custom serializer to use for encoding the object, when everything else fails.
213215
"""
214216
encoded_dict = {}
215217
allowed_keys = set(obj.keys())
@@ -250,9 +252,10 @@ def _dump_sequence(
250252
exclude_unset: bool = False,
251253
exclude_none: bool = False,
252254
exclude_defaults: bool = False,
255+
custom_serializer: Optional[Callable[[Any], str]] = None,
253256
) -> List[Any]:
254257
"""
255-
Dump a sequence to a list, using the same parameters as jsonable_encoder
258+
Dump a sequence to a list, using the same parameters as jsonable_encoder.
256259
"""
257260
encoded_list = []
258261
for item in obj:
@@ -265,6 +268,7 @@ def _dump_sequence(
265268
exclude_unset=exclude_unset,
266269
exclude_defaults=exclude_defaults,
267270
exclude_none=exclude_none,
271+
custom_serializer=custom_serializer,
268272
),
269273
)
270274
return encoded_list

tests/functional/event_handler/_pydantic/test_openapi_encoders.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,8 +197,7 @@ class MyClass:
197197

198198
def test_openapi_encode_custom_serializer_nested_dict():
199199
# GIVEN a nested dictionary with a custom class
200-
class CustomClass(object):
201-
__slots__ = []
200+
class CustomClass: ...
202201

203202
nested_dict = {"a": {"b": CustomClass()}}
204203

@@ -211,3 +210,21 @@ def serializer(value):
211210

212211
# THEN we should get the custom serializer output
213212
assert result == {"a": {"b": "serialized"}}
213+
214+
215+
def test_openapi_encode_custom_serializer_sequences():
216+
# GIVEN a sequence with a custom class
217+
class CustomClass:
218+
__slots__ = []
219+
220+
seq = [CustomClass()]
221+
222+
# AND a custom serializer
223+
def serializer(value):
224+
return "serialized"
225+
226+
# WHEN we call jsonable_encoder with the nested dictionary and unserializable value
227+
result = jsonable_encoder(seq, custom_serializer=serializer)
228+
229+
# THEN we should get the custom serializer output
230+
assert result == ["serialized"]

0 commit comments

Comments
 (0)