Return the fields of a dataclass instance as a new dictionary mapping field names to field values. Example usage:: @dataclass class C: x: int y: int c = C(1, 2) assert asdict(c) == {'x': 1, 'y': 2} If given, 'dict_factory' will be used inst
(obj, *, dict_factory=dict)
| 1474 | |
| 1475 | |
| 1476 | def asdict(obj, *, dict_factory=dict): |
| 1477 | """Return the fields of a dataclass instance as a new dictionary mapping |
| 1478 | field names to field values. |
| 1479 | |
| 1480 | Example usage:: |
| 1481 | |
| 1482 | @dataclass |
| 1483 | class C: |
| 1484 | x: int |
| 1485 | y: int |
| 1486 | |
| 1487 | c = C(1, 2) |
| 1488 | assert asdict(c) == {'x': 1, 'y': 2} |
| 1489 | |
| 1490 | If given, 'dict_factory' will be used instead of built-in dict. |
| 1491 | The function applies recursively to field values that are |
| 1492 | dataclass instances. This will also look into built-in containers: |
| 1493 | tuples, lists, and dicts. Other objects are copied with 'copy.deepcopy()'. |
| 1494 | """ |
| 1495 | if not _is_dataclass_instance(obj): |
| 1496 | raise TypeError("asdict() should be called on dataclass instances") |
| 1497 | return _asdict_inner(obj, dict_factory) |
| 1498 | |
| 1499 | |
| 1500 | def _asdict_inner(obj, dict_factory): |
searching dependent graphs…