|
18 | 18 | """ |
19 | 19 |
|
20 | 20 | import contextlib |
| 21 | +import copy |
21 | 22 | import functools |
22 | 23 | import itertools |
23 | 24 | import os |
|
26 | 27 | import sys |
27 | 28 | import types |
28 | 29 | from contextlib import contextmanager |
| 30 | +from dataclasses import fields, is_dataclass |
29 | 31 | from io import BytesIO as StringIO |
30 | 32 | from multiprocessing import Pool, RLock |
31 | 33 | from shutil import disk_usage |
@@ -151,6 +153,41 @@ def string_to_dict(string: str, pattern: str) -> Dict[str, str]: |
151 | 153 | return _dict |
152 | 154 |
|
153 | 155 |
|
| 156 | +def asdict(obj): |
| 157 | + """Convert an object to its dictionary representation recursively.""" |
| 158 | + |
| 159 | + # Implementation based on https://docs.python.org/3/library/dataclasses.html#dataclasses.asdict |
| 160 | + |
| 161 | + def _is_dataclass_instance(obj): |
| 162 | + # https://docs.python.org/3/library/dataclasses.html#dataclasses.is_dataclass |
| 163 | + return is_dataclass(obj) and not isinstance(obj, type) |
| 164 | + |
| 165 | + def _asdict_inner(obj): |
| 166 | + if _is_dataclass_instance(obj): |
| 167 | + result = {} |
| 168 | + for f in fields(obj): |
| 169 | + value = _asdict_inner(getattr(obj, f.name)) |
| 170 | + result[f.name] = value |
| 171 | + return result |
| 172 | + elif isinstance(obj, tuple) and hasattr(obj, "_fields"): |
| 173 | + # obj is a namedtuple |
| 174 | + return type(obj)(*[_asdict_inner(v) for v in obj]) |
| 175 | + elif isinstance(obj, (list, tuple)): |
| 176 | + # Assume we can create an object of this type by passing in a |
| 177 | + # generator (which is not true for namedtuples, handled |
| 178 | + # above). |
| 179 | + return type(obj)(_asdict_inner(v) for v in obj) |
| 180 | + elif isinstance(obj, dict): |
| 181 | + return {_asdict_inner(k): _asdict_inner(v) for k, v in obj.items()} |
| 182 | + else: |
| 183 | + return copy.deepcopy(obj) |
| 184 | + |
| 185 | + if not isinstance(obj, dict) and not _is_dataclass_instance(obj): |
| 186 | + raise TypeError(f"{obj} is not a dict or a dataclass") |
| 187 | + |
| 188 | + return _asdict_inner(obj) |
| 189 | + |
| 190 | + |
154 | 191 | @contextlib.contextmanager |
155 | 192 | def temporary_assignment(obj, attr, value): |
156 | 193 | """Temporarily assign obj.attr to value.""" |
|
0 commit comments