mirror of
https://github.com/python/cpython.git
synced 2025-11-25 12:44:13 +00:00
gh-103000: Optimise dataclasses.asdict for the common case (#104364)
Co-authored-by: David Ellis <ducksual@gmail.com>
This commit is contained in:
parent
e464ec9f4c
commit
7b8d7f56b6
2 changed files with 14 additions and 5 deletions
|
|
@ -1324,11 +1324,18 @@ def _asdict_inner(obj, dict_factory):
|
||||||
if type(obj) in _ATOMIC_TYPES:
|
if type(obj) in _ATOMIC_TYPES:
|
||||||
return obj
|
return obj
|
||||||
elif _is_dataclass_instance(obj):
|
elif _is_dataclass_instance(obj):
|
||||||
result = []
|
# fast path for the common case
|
||||||
for f in fields(obj):
|
if dict_factory is dict:
|
||||||
value = _asdict_inner(getattr(obj, f.name), dict_factory)
|
return {
|
||||||
result.append((f.name, value))
|
f.name: _asdict_inner(getattr(obj, f.name), dict)
|
||||||
return dict_factory(result)
|
for f in fields(obj)
|
||||||
|
}
|
||||||
|
else:
|
||||||
|
result = []
|
||||||
|
for f in fields(obj):
|
||||||
|
value = _asdict_inner(getattr(obj, f.name), dict_factory)
|
||||||
|
result.append((f.name, value))
|
||||||
|
return dict_factory(result)
|
||||||
elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
|
elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
|
||||||
# obj is a namedtuple. Recurse into it, but the returned
|
# obj is a namedtuple. Recurse into it, but the returned
|
||||||
# object is another namedtuple of the same type. This is
|
# object is another namedtuple of the same type. This is
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,2 @@
|
||||||
|
Improve performance of :func:`dataclasses.asdict` for the common case where
|
||||||
|
*dict_factory* is ``dict``. Patch by David C Ellis.
|
||||||
Loading…
Add table
Add a link
Reference in a new issue