Skip to content

Commit

Permalink
Fix subclasses type. #115 (#124)
Browse files Browse the repository at this point in the history
  • Loading branch information
fabiocaccamo authored Oct 9, 2022
1 parent f917417 commit a1e5b9f
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
Original file line number Diff line number Diff line change
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
Original file line number Diff line number Diff line change
@@ -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 a1e5b9f

Please sign in to comment.