Skip to content

Commit a1e5b9f

Browse files
authored
Fix subclasses type. #115 (#124)
1 parent f917417 commit a1e5b9f

File tree

2 files changed

+44
-3
lines changed

2 files changed

+44
-3
lines changed

benedict/dicts/__init__.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -53,7 +53,8 @@ def __init__(self, *args, **kwargs):
5353
super(benedict, self).__init__(*args, **kwargs)
5454

5555
def __deepcopy__(self, memo):
56-
obj = benedict(keypath_separator=self._keypath_separator)
56+
obj_type = type(self)
57+
obj = obj_type(keypath_separator=self._keypath_separator)
5758
for key, value in self.items():
5859
obj[key] = _clone(value, memo=memo)
5960
return obj
@@ -66,8 +67,9 @@ def _cast(self, value):
6667
Cast a dict instance to a benedict instance
6768
keeping the pointer to the original dict.
6869
"""
69-
if isinstance(value, dict) and not isinstance(value, benedict):
70-
return benedict(
70+
obj_type = type(self)
71+
if isinstance(value, dict) and not isinstance(value, obj_type):
72+
return obj_type(
7173
value, keypath_separator=self._keypath_separator, check_keys=False
7274
)
7375
return value
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
# -*- coding: utf-8 -*-
2+
3+
from benedict import benedict
4+
5+
import unittest
6+
7+
8+
class subbenedict(benedict):
9+
pass
10+
11+
12+
class benedict_subclass_test_case(unittest.TestCase):
13+
"""
14+
This class describes a benedict subclass test case.
15+
"""
16+
17+
def test_cast(self):
18+
d = subbenedict(
19+
{
20+
"a": {
21+
"b": {
22+
"c": {
23+
"d": True,
24+
},
25+
}
26+
}
27+
}
28+
)
29+
c = d["a.b.c"]
30+
self.assertTrue(issubclass(type(c), benedict))
31+
self.assertTrue(isinstance(c, subbenedict))
32+
self.assertEqual(c, {"d": True})
33+
34+
def test_clone(self):
35+
d = subbenedict({"a": True})
36+
c = d.clone()
37+
self.assertTrue(issubclass(type(c), benedict))
38+
self.assertTrue(isinstance(c, subbenedict))
39+
self.assertEqual(c, {"a": True})

0 commit comments

Comments
 (0)