Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

gh-103000: Optimise dataclasses asdict/astuple for common types #103005

Merged
merged 15 commits into from
Apr 10, 2023
Merged
Show file tree
Hide file tree
Changes from 14 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 29 additions & 2 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,29 @@ def __repr__(self):
# https://bugs.python.org/issue33453 for details.
_MODULE_IDENTIFIER_RE = re.compile(r'^(?:\s*(\w+)\s*\.)?\s*(\w+)')

# Atomic immutable types which don't require any recursive handling and for which deepcopy
# returns the same object. We can provide a fast-path for these types in asdict and astuple.
_ATOMIC_TYPES = frozenset({
# Common JSON Serializable types
types.NoneType,
bool,
int,
float,
str,
# Other common types
complex,
bytes,
# Other types that are also unaffected by deepcopy
types.EllipsisType,
types.NotImplementedType,
types.CodeType,
types.BuiltinFunctionType,
types.FunctionType,
type,
range,
property,
})

# This function's logic is copied from "recursive_repr" function in
# reprlib module to avoid dependency.
def _recursive_repr(user_function):
Expand Down Expand Up @@ -1292,7 +1315,9 @@ class C:


def _asdict_inner(obj, dict_factory):
if _is_dataclass_instance(obj):
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)
Expand Down Expand Up @@ -1364,7 +1389,9 @@ class C:


def _astuple_inner(obj, tuple_factory):
if _is_dataclass_instance(obj):
if type(obj) in _ATOMIC_TYPES:
return obj
elif _is_dataclass_instance(obj):
result = []
for f in fields(obj):
value = _astuple_inner(getattr(obj, f.name), tuple_factory)
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Performance improvement for :func:`dataclasses.astuple` and :func:`dataclasses.asdict` in cases where the contents are common python types.
AlexWaygood marked this conversation as resolved.
Show resolved Hide resolved