gh-103000: Optimise dataclasses.asdict for the common case (#104364)

Co-authored-by: David Ellis <ducksual@gmail.com>
This commit is contained in:
Alex Waygood 2023-05-10 22:43:51 +01:00 committed by GitHub
parent e464ec9f4c
commit 7b8d7f56b6
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 5 deletions

View file

@ -1324,6 +1324,13 @@ def _asdict_inner(obj, dict_factory):
if type(obj) in _ATOMIC_TYPES:
return obj
elif _is_dataclass_instance(obj):
# fast path for the common case
if dict_factory is dict:
return {
f.name: _asdict_inner(getattr(obj, f.name), dict)
for f in fields(obj)
}
else:
result = []
for f in fields(obj):
value = _asdict_inner(getattr(obj, f.name), dict_factory)

View file

@ -0,0 +1,2 @@
Improve performance of :func:`dataclasses.asdict` for the common case where
*dict_factory* is ``dict``. Patch by David C Ellis.