Update behaviour for named tuples

This commit is contained in:
Pedro Lobato 2026-02-10 09:25:36 -05:00
parent da3a758974
commit ad20536712
1 changed files with 25 additions and 0 deletions

View File

@ -206,6 +206,18 @@ def jsonable_encoder(
"""
),
] = True,
named_tuple_as_dict: Annotated[
bool,
Doc(
"""
Whether to encode named tuples as dicts instead of lists.
This is useful when you want to preserve the field names of named tuples
in the JSON output, which can make it easier to understand and work with
the data on the client side.
"""
),
] = False,
) -> Any:
"""
Convert any object to something that can be encoded in JSON.
@ -323,6 +335,19 @@ def jsonable_encoder(
)
return encoded_list
if named_tuple_as_dict and getattr(obj, "_asdict", None) is not None and callable(obj._asdict):
return jsonable_encoder(
obj._asdict(),
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,
)
if type(obj) in ENCODERS_BY_TYPE:
return ENCODERS_BY_TYPE[type(obj)](obj)
for encoder, classes_tuple in encoders_by_class_tuples.items():