@@ -324,7 +324,10 @@ Module contents
324
324
Converts the dataclass ``instance `` to a dict (by using the
325
325
factory function ``dict_factory ``). Each dataclass is converted
326
326
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::
328
331
329
332
@dataclass
330
333
class Point:
@@ -341,21 +344,32 @@ Module contents
341
344
c = C([Point(0, 0), Point(10, 4)])
342
345
assert asdict(c) == {'mylist': [{'x': 0, 'y': 0}, {'x': 10, 'y': 4}]}
343
346
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.
345
353
346
354
.. function :: astuple(instance, *, tuple_factory=tuple)
347
355
348
356
Converts the dataclass ``instance `` to a tuple (by using the
349
357
factory function ``tuple_factory ``). Each dataclass is converted
350
358
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 `.
352
361
353
362
Continuing from the previous example::
354
363
355
364
assert astuple(p) == (10, 20)
356
365
assert astuple(c) == ([(0, 0), (10, 4)],)
357
366
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.
359
373
360
374
.. 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)
361
375
0 commit comments