Skip to content

Commit 376b24e

Browse files
bpo-43905: Expand dataclasses.astuple() and asdict() docs (GH-26154)
Expanded ``astuple()`` docs, warning about deepcopy being applied and providing a workaround. Automerge-Triggered-By: GH:ericvsmith (cherry picked from commit c1f93f0) Co-authored-by: andrei kulakov <[email protected]>
1 parent 40a5753 commit 376b24e

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

Doc/library/dataclasses.rst

+18-4
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,10 @@ Module-level decorators, classes, and functions
292292
Converts the dataclass ``instance`` to a dict (by using the
293293
factory function ``dict_factory``). Each dataclass is converted
294294
to a dict of its fields, as ``name: value`` pairs. dataclasses, dicts,
295-
lists, and tuples are recursed into. For example::
295+
lists, and tuples are recursed into. Other objects are copied with
296+
:func:`copy.deepcopy`.
297+
298+
Example of using :func:`asdict` on nested dataclasses::
296299

297300
@dataclass
298301
class Point:
@@ -309,21 +312,32 @@ Module-level decorators, classes, and functions
309312
c = C([Point(0, 0), Point(10, 4)])
310313
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
311314

312-
Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.
315+
To create a shallow copy, the following workaround may be used::
316+
317+
dict((field.name, getattr(instance, field.name)) for field in fields(instance))
318+
319+
:func:`asdict` raises :exc:`TypeError` if ``instance`` is not a dataclass
320+
instance.
313321

314322
.. function:: astuple(instance, *, tuple_factory=tuple)
315323

316324
Converts the dataclass ``instance`` to a tuple (by using the
317325
factory function ``tuple_factory``). Each dataclass is converted
318326
to a tuple of its field values. dataclasses, dicts, lists, and
319-
tuples are recursed into.
327+
tuples are recursed into. Other objects are copied with
328+
:func:`copy.deepcopy`.
320329

321330
Continuing from the previous example::
322331

323332
assert astuple(p) == (10, 20)
324333
assert astuple(c) == ([(0, 0), (10, 4)],)
325334

326-
Raises :exc:`TypeError` if ``instance`` is not a dataclass instance.
335+
To create a shallow copy, the following workaround may be used::
336+
337+
tuple(getattr(instance, field.name) for field in dataclasses.fields(instance))
338+
339+
:func:`astuple` raises :exc:`TypeError` if ``instance`` is not a dataclass
340+
instance.
327341

328342
.. function:: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False)
329343

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Expanded :func:`~dataclasses.astuple` and :func:`~dataclasses.asdict` docs,
2+
warning about deepcopy being applied and providing a workaround.

0 commit comments

Comments
 (0)