Added empty option to clone utility method.

This commit is contained in:
Fabio Caccamo 2020-09-17 14:09:59 +02:00
parent b49b7e99ee
commit 8065eddf41
7 changed files with 28 additions and 12 deletions

View File

@ -3,5 +3,8 @@
import copy
def clone(obj):
return copy.deepcopy(obj)
def clone(obj, empty=False):
d = copy.deepcopy(obj)
if empty:
d.clear()
return d

View File

@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-
from benedict.core import clone
def filter(d, predicate):
if not callable(predicate):
raise ValueError('predicate argument must be a callable.')
new_dict = d.copy()
new_dict.clear()
new_dict = clone(d, empty=True)
keys = list(d.keys())
for key in keys:
value = d.get(key, None)

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from benedict.core import clone
from benedict.utils import type_util
@ -10,8 +11,7 @@ def _flatten_key(base_key, key, separator):
def flatten(d, separator='_', **kwargs):
new_dict = d.copy()
new_dict.clear()
new_dict = clone(d, empty=True)
keys = list(d.keys())
base_key = kwargs.pop('base_key', '')
for key in keys:

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from benedict.core import clone
from benedict.utils import type_util
@ -16,8 +17,7 @@ def _invert_list(d, key, value, flat):
def invert(d, flat=False):
new_dict = d.copy()
new_dict.clear()
new_dict = clone(d, empty=True)
for key, value in d.items():
if type_util.is_list_or_tuple(value):
_invert_list(new_dict, key, value, flat)

View File

@ -1,11 +1,11 @@
# -*- coding: utf-8 -*-
from benedict.core import clone
from benedict.utils import type_util
def subset(d, keys, *args):
new_dict = d.copy()
new_dict.clear()
new_dict = clone(d, empty=True)
if type_util.is_string(keys):
keys = [keys]
keys += args

View File

@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-
from benedict.core import clone
from benedict.dicts.keylist import keylist_util
from benedict.utils import type_util
@ -12,8 +13,7 @@ def _unflatten_item(key, value, separator):
def unflatten(d, separator='_'):
new_dict = d.copy()
new_dict.clear()
new_dict = clone(d, empty=True)
keys = list(d.keys())
for key in keys:
value = d.get(key, None)

View File

@ -22,3 +22,15 @@ class clone_test_case(unittest.TestCase):
o['a']['b']['c'] = 2
self.assertEqual(i['a']['b']['c'], 1)
self.assertEqual(o['a']['b']['c'], 2)
def test_clone_empty(self):
i = {
'a': {
'b': {
'c': 1
}
}
}
o = _clone(i, empty=True)
self.assertEqual(type(i), type(o))
self.assertEqual(o, {})