Skip to content

Commit 7b8d7f5

Browse files
gh-103000: Optimise dataclasses.asdict for the common case (#104364)
Co-authored-by: David Ellis <[email protected]>
1 parent e464ec9 commit 7b8d7f5

File tree

2 files changed

+14
-5
lines changed

2 files changed

+14
-5
lines changed

Lib/dataclasses.py

+12-5
Original file line numberDiff line numberDiff line change
@@ -1324,11 +1324,18 @@ def _asdict_inner(obj, dict_factory):
13241324
if type(obj) in _ATOMIC_TYPES:
13251325
return obj
13261326
elif _is_dataclass_instance(obj):
1327-
result = []
1328-
for f in fields(obj):
1329-
value = _asdict_inner(getattr(obj, f.name), dict_factory)
1330-
result.append((f.name, value))
1331-
return dict_factory(result)
1327+
# fast path for the common case
1328+
if dict_factory is dict:
1329+
return {
1330+
f.name: _asdict_inner(getattr(obj, f.name), dict)
1331+
for f in fields(obj)
1332+
}
1333+
else:
1334+
result = []
1335+
for f in fields(obj):
1336+
value = _asdict_inner(getattr(obj, f.name), dict_factory)
1337+
result.append((f.name, value))
1338+
return dict_factory(result)
13321339
elif isinstance(obj, tuple) and hasattr(obj, '_fields'):
13331340
# obj is a namedtuple. Recurse into it, but the returned
13341341
# object is another namedtuple of the same type. This is
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Improve performance of :func:`dataclasses.asdict` for the common case where
2+
*dict_factory* is ``dict``. Patch by David C Ellis.

0 commit comments

Comments
 (0)