Passed
Push — master ( 3318af...ce1cbc )
by Fabio
01:13
created

KeypathDict.__delitem_by_keys()   A

Complexity

Conditions 2

Size

Total Lines 6
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nop 2
dl 0
loc 6
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
3
from benedict.dicts import KeylistDict
4
from benedict.utils import keypath_util
5
6
7
class KeypathDict(KeylistDict):
8
9
    _keypath_separator = None
10
11
    def __init__(self, *args, **kwargs):
12
        self._keypath_separator = kwargs.pop('keypath_separator', '.')
13
        super(KeypathDict, self).__init__(*args, **kwargs)
14
        keypath_util.check_keys(self, self._keypath_separator)
15
16
    @property
17
    def keypath_separator(self):
18
        return self._keypath_separator
19
20
    @keypath_separator.setter
21
    def keypath_separator(self, value):
22
        keypath_util.check_keys(self, value)
23
        self._keypath_separator = value
24
25
    def __contains__(self, key):
26
        return super(KeypathDict, self).__contains__(
27
            self._parse_key(key))
28
29
    def __delitem__(self, key):
30
        super(KeypathDict, self).__delitem__(
31
            self._parse_key(key))
32
33
    def __getitem__(self, key):
34
        return super(KeypathDict, self).__getitem__(
35
            self._parse_key(key))
36
37
    def __setitem__(self, key, value):
38
        keypath_util.check_keys(value, self._keypath_separator)
39
        super(KeypathDict, self).__setitem__(
40
            self._parse_key(key), value)
41
42
    def _parse_key(self, key):
43
        keys = keypath_util.parse_keys(key, self._keypath_separator)
44
        keys_count = len(keys)
45
        if keys_count == 0:
46
            return None
47
        elif keys_count == 1:
48
            return keys[0]
49
        return keys
50
51
    @classmethod
52
    def fromkeys(cls, sequence, value=None):
53
        d = cls()
54
        for key in sequence:
55
            d[key] = value
56
        return d
57
58
    def get(self, key, default=None):
59
        return super(KeypathDict, self).get(
60
            self._parse_key(key), default)
61
62
    def pop(self, key, *args):
63
        return super(KeypathDict, self).pop(
64
            self._parse_key(key), *args)
65
66
    def set(self, key, value):
67
        self.__setitem__(key, value)
68
69
    def setdefault(self, key, default=None):
70
        if key not in self:
71
            self.set(key, default)
72
            return default
73
        return self.__getitem__(key)
74
75
    def update(self, other):
76
        keypath_util.check_keys(other, self._keypath_separator)
77
        super(KeypathDict, self).update(other)
78
79