Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

bpo-35540 dataclasses.asdict support defaultdict fields #32056

Merged
merged 6 commits into from
Oct 7, 2022
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions Lib/dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -1309,6 +1309,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(obj, 'default_factory'):
ericvsmith marked this conversation as resolved.
Show resolved Hide resolved
# 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))
Expand Down
21 changes: 19 additions & 2 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,9 @@
import weakref
import unittest
from unittest.mock import Mock
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
from typing import get_type_hints
from collections import deque, OrderedDict, namedtuple
from collections import deque, OrderedDict, namedtuple, defaultdict
from functools import total_ordering

import typing # Needed for the string "typing.ClassVar[int]" to work as an annotation.
Expand Down Expand Up @@ -1651,6 +1651,23 @@ class C:
self.assertIsNot(d['f'], t)
self.assertEqual(d['f'].my_a(), 6)

def test_helper_asdict_defaultdict(self):
# Ensure asdict() does not throw exceptions when a
# defaultdict is a member of a dataclass

@dataclass
class C:
mp: DefaultDict[str, List]


dd = defaultdict(list)
dd["x"].append(12)
c = C(mp=dd)
d = asdict(c)

assert d == {"mp": {"x": [12]}}
assert d["mp"] is not c.mp # make sure defaultdict is copied

def test_helper_astuple(self):
# Basic tests for astuple(), it should return a new tuple.
@dataclass
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix :func:`dataclasses.asdict` crash when :class:`collections.defaultdict` is present in the attributes.