Skip to content

Commit 8418c96

Browse files
committed
2.14.1 - add __dict__ fallback to DictDataClass.__iter__ for dict conversion
1 parent 96180a1 commit 8418c96

2 files changed

Lines changed: 11 additions & 2 deletions

File tree

privex/helpers/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ def _setup_logging(level=logging.WARNING):
148148
log = _setup_logging()
149149
name = 'helpers'
150150

151-
VERSION = '2.14.0'
151+
VERSION = '2.14.1'
152152

153153

154154

privex/helpers/collections.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -193,6 +193,7 @@
193193
import inspect
194194
import sys
195195
from collections import namedtuple, OrderedDict
196+
from json import JSONDecodeError
196197
from types import MemberDescriptorType
197198
from typing import Dict, Optional, NamedTuple, Union, Type, List, Generator, Iterable, TypeVar
198199
from privex.helpers.types import T, K
@@ -1252,12 +1253,20 @@ def _dc_dict_config(self) -> Union[_DictConfig, DictObject]:
12521253
DictConfig = copy_class(_DictConfig, name='DictConfig', quiet=True)
12531254

12541255
def __iter__(self):
1256+
cls_name = self.__class__.__name__
12551257
# The raw_data attribute isn't required, and isn't guaranteed to have been set on a dataclass, so
12561258
# we fallback to a blank DictObject if it's not found.
12571259
dict_rd = DictObject()
12581260
if hasattr(self, 'raw_data'):
12591261
dict_rd = dict(self.raw_data)
1260-
dict_dc = dataclasses.asdict(self, dict_factory=dict)
1262+
1263+
# dataclasses.asdict can sometimes freak out when a dataclass contains un-serializable objects such as arbitrary
1264+
# class instances (which may even be excluded already in DictConfig. In such a case, we can fallback to __dict__ :)
1265+
try:
1266+
dict_dc = dataclasses.asdict(self, dict_factory=dict)
1267+
except (TypeError, ValueError, JSONDecodeError) as e:
1268+
log.warning("Dictifying %s using dataclasses.asdict failed (%s %s)... falling back to __dict__", cls_name, type(e), str(e))
1269+
dict_dc = dict(self.__dict__)
12611270

12621271
from privex.helpers import empty
12631272
dconf = self._dc_dict_config

0 commit comments

Comments
 (0)