@@ -324,7 +324,10 @@ Module contents
324324 Converts the dataclass ``instance `` to a dict (by using the
325325 factory function ``dict_factory ``). Each dataclass is converted
326326 to a dict of its fields, as ``name: value `` pairs. dataclasses, dicts,
327- lists, and tuples are recursed into. For example::
327+ lists, and tuples are recursed into. Other objects are copied with
328+ :func: `copy.deepcopy `.
329+
330+ Example of using :func: `asdict ` on nested dataclasses::
328331
329332 @dataclass
330333 class Point:
@@ -341,21 +344,32 @@ Module contents
341344 c = C([Point(0, 0), Point(10, 4)])
342345 assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
343346
344- Raises :exc: `TypeError ` if ``instance `` is not a dataclass instance.
347+ To create a shallow copy, the following workaround may be used::
348+
349+ dict((field.name, getattr(instance, field.name)) for field in fields(instance))
350+
351+ :func: `asdict ` raises :exc: `TypeError ` if ``instance `` is not a dataclass
352+ instance.
345353
346354.. function :: astuple(instance, *, tuple_factory=tuple)
347355
348356 Converts the dataclass ``instance `` to a tuple (by using the
349357 factory function ``tuple_factory ``). Each dataclass is converted
350358 to a tuple of its field values. dataclasses, dicts, lists, and
351- tuples are recursed into.
359+ tuples are recursed into. Other objects are copied with
360+ :func: `copy.deepcopy `.
352361
353362 Continuing from the previous example::
354363
355364 assert astuple(p) == (10, 20)
356365 assert astuple(c) == ([(0, 0), (10, 4)],)
357366
358- Raises :exc: `TypeError ` if ``instance `` is not a dataclass instance.
367+ To create a shallow copy, the following workaround may be used::
368+
369+ tuple(getattr(instance, field.name) for field in dataclasses.fields(instance))
370+
371+ :func: `astuple ` raises :exc: `TypeError ` if ``instance `` is not a dataclass
372+ instance.
359373
360374.. function :: make_dataclass(cls_name, fields, *, bases=(), namespace=None, init=True, repr=True, eq=True, order=False, unsafe_hash=False, frozen=False, match_args=True, kw_only=False, slots=False)
361375
0 commit comments