summaryrefslogtreecommitdiffstats
path: root/Lib/dataclasses.py
diff options
context:
space:
mode:
authorAlex Waygood <Alex.Waygood@Gmail.com>2023-05-10 21:43:51 (GMT)
committerGitHub <noreply@github.com>2023-05-10 21:43:51 (GMT)
commit7b8d7f56b64ab4370fea77e77ea4984dd2a73979 (patch)
tree4729a06c9797ac0ce054a4c5f70fe4298d6599eb /Lib/dataclasses.py
parente464ec9f4c4af6c2fdb6db9a3fa70ffd703ae01f (diff)
downloadcpython-7b8d7f56b64ab4370fea77e77ea4984dd2a73979.zip
cpython-7b8d7f56b64ab4370fea77e77ea4984dd2a73979.tar.gz
cpython-7b8d7f56b64ab4370fea77e77ea4984dd2a73979.tar.bz2
gh-103000: Optimise `dataclasses.asdict` for the common case (#104364)
Co-authored-by: David Ellis <ducksual@gmail.com>
Diffstat (limited to 'Lib/dataclasses.py')
-rw-r--r--Lib/dataclasses.py17
1 files changed, 12 insertions, 5 deletions
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py
index b0b8a77..3eacba8 100644
--- a/Lib/dataclasses.py
+++ b/Lib/dataclasses.py
@@ -1324,11 +1324,18 @@ def _asdict_inner(obj, dict_factory):
if type(obj) in _ATOMIC_TYPES:
return obj
elif _is_dataclass_instance(obj):
- result = []
- for f in fields(obj):
- value = _asdict_inner(getattr(obj, f.name), dict_factory)
- result.append((f.name, value))
- return dict_factory(result)
+ # 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)
+ result.append((f.name, value))
+ return dict_factory(result)
elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
# obj is a namedtuple. Recurse into it, but the returned
# object is another namedtuple of the same type. This is