diff --git a/benedict/dicts/__init__.py b/benedict/dicts/__init__.py index cf5c05a8..a218a0b2 100644 --- a/benedict/dicts/__init__.py +++ b/benedict/dicts/__init__.py @@ -53,7 +53,8 @@ def __init__(self, *args, **kwargs): super(benedict, self).__init__(*args, **kwargs) def __deepcopy__(self, memo): - obj = benedict(keypath_separator=self._keypath_separator) + obj_type = type(self) + obj = obj_type(keypath_separator=self._keypath_separator) for key, value in self.items(): obj[key] = _clone(value, memo=memo) return obj @@ -66,8 +67,9 @@ def _cast(self, value): Cast a dict instance to a benedict instance keeping the pointer to the original dict. """ - if isinstance(value, dict) and not isinstance(value, benedict): - return benedict( + obj_type = type(self) + if isinstance(value, dict) and not isinstance(value, obj_type): + return obj_type( value, keypath_separator=self._keypath_separator, check_keys=False ) return value diff --git a/tests/dicts/test_benedict_subclass.py b/tests/dicts/test_benedict_subclass.py new file mode 100644 index 00000000..3f8eece6 --- /dev/null +++ b/tests/dicts/test_benedict_subclass.py @@ -0,0 +1,39 @@ +# -*- coding: utf-8 -*- + +from benedict import benedict + +import unittest + + +class subbenedict(benedict): + pass + + +class benedict_subclass_test_case(unittest.TestCase): + """ + This class describes a benedict subclass test case. + """ + + def test_cast(self): + d = subbenedict( + { + "a": { + "b": { + "c": { + "d": True, + }, + } + } + } + ) + c = d["a.b.c"] + self.assertTrue(issubclass(type(c), benedict)) + self.assertTrue(isinstance(c, subbenedict)) + self.assertEqual(c, {"d": True}) + + def test_clone(self): + d = subbenedict({"a": True}) + c = d.clone() + self.assertTrue(issubclass(type(c), benedict)) + self.assertTrue(isinstance(c, subbenedict)) + self.assertEqual(c, {"a": True})