diff options
author | Tiger <tnie@tuta.io> | 2022-10-07 00:11:59 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-10-07 00:11:59 (GMT) |
commit | c46a423a520b797c3f8c81fef19293864742755d (patch) | |
tree | 4161491118c43d512c4409df9f40e28657f74c87 /Lib/dataclasses.py | |
parent | a4b7794887929f82c532fcd055326954ff1197ce (diff) | |
download | cpython-c46a423a520b797c3f8c81fef19293864742755d.zip cpython-c46a423a520b797c3f8c81fef19293864742755d.tar.gz cpython-c46a423a520b797c3f8c81fef19293864742755d.tar.bz2 |
bpo-35540 dataclasses.asdict now supports defaultdict fields (gh-32056)
Diffstat (limited to 'Lib/dataclasses.py')
-rw-r--r-- | Lib/dataclasses.py | 8 |
1 files changed, 8 insertions, 0 deletions
diff --git a/Lib/dataclasses.py b/Lib/dataclasses.py index 65fb8f2..bf7f290 100644 --- a/Lib/dataclasses.py +++ b/Lib/dataclasses.py @@ -1325,6 +1325,14 @@ def _asdict_inner(obj, dict_factory): # generator (which is not true for namedtuples, handled # above). return type(obj)(_asdict_inner(v, dict_factory) for v in obj) + elif isinstance(obj, dict) and hasattr(type(obj), 'default_factory'): + # obj is a defaultdict, which has a different constructor from + # dict as it requires the default_factory as its first arg. + # https://bugs.python.org/issue35540 + result = type(obj)(getattr(obj, 'default_factory')) + for k, v in obj.items(): + result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory) + return result elif isinstance(obj, dict): return type(obj)((_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) |