bpo-35540 dataclasses.asdict now supports defaultdict fields (gh-32056)

This commit is contained in:
Tiger 2022-10-06 19:11:59 -05:00 committed by GitHub
parent a4b7794887
commit c46a423a52
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 28 additions and 2 deletions

View file

@ -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))