Skip to content

Commit

Permalink
Return instances of the right type when calling clone or casting it…
Browse files Browse the repository at this point in the history
…ems in a `benedict` subclass. #115
  • Loading branch information
fabiocaccamo committed Sep 15, 2022
1 parent 7a10e2c commit 5185978
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 3 deletions.
8 changes: 5 additions & 3 deletions benedict/dicts/__init__.py
Expand Up @@ -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
Expand All @@ -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
Expand Down
39 changes: 39 additions & 0 deletions 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})

0 comments on commit 5185978

Please sign in to comment.