Passed
Pull Request — master (#114)
by
unknown
01:20
created

benedict.dicts.keylist.keylist_util   B

Complexity

Total Complexity 43

Size/Duplication

Total Lines 142
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 110
dl 0
loc 142
rs 8.96
c 0
b 0
f 0
wmc 43

9 Functions

Rating   Name   Duplication   Size   Complexity  
A _get_index() 0 4 2
A set_item() 0 12 3
A _new_item_value() 0 3 2
A _get_or_new_item_value() 0 9 3
A get_item() 0 3 2
A get_items() 0 20 5
B _set_item_value() 0 16 6
D _get_item_key_and_value_for_parent_wildcard() 0 34 13
B _get_item_key_and_value() 0 17 7

How to fix   Complexity   

Complexity

Complex classes like benedict.dicts.keylist.keylist_util often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
# -*- coding: utf-8 -*-
2
3
from itertools import chain
4
5
from benedict.utils import type_util
6
7
8
def _get_index(key):
9
    if type_util.is_integer(key):
10
        return key
11
    return None
12
13
14
def _get_item_key_and_value_for_parent_wildcard(item, index, parent, child):
15
    if type_util.is_list_of_dicts(item) and any(
16
        index in _item.keys() for _item in item
17
    ):
18
        data = [_item.get(index) for _item in item if index in _item.keys()]
19
        if type_util.is_list_of_list(data):
20
            data = list(chain.from_iterable(data))
21
        # eject dict from list to be able to access dict properties
22
        if (
23
            len(data) == 1
24
            and len(item) == 1
25
            and type_util.is_wildcard(parent)
26
            and not type_util.is_wildcard(index)
27
            and not type_util.is_wildcard(child)
28
        ):
29
            data = data[0]
30
        return index, data
31
    elif type_util.is_list_of_list(item):
32
        if type_util.is_integer(index):
33
            data = [_item[index] for _item in item if index < len(_item)]
34
            return index, data
35
        elif type_util.is_wildcard(index):
36
            data = list(chain.from_iterable(item))
37
            return index, data
38
        else:
39
            data = [
40
                _item.get(index)
41
                for _item in chain.from_iterable(item)
42
                if index in _item.keys()
43
            ]
44
            return index, data
45
    elif type_util.is_wildcard(index):
46
        return index, item
47
    return index, None
48
49
50
def _get_item_key_and_value(item, index, parent=None, child=None):
51
    if type_util.is_list_or_tuple(item):
52
        if type_util.is_wildcard(parent):
53
            index, item = _get_item_key_and_value_for_parent_wildcard(
54
                item, index, parent, child
55
            )
56
            if item:
57
                return index, item
58
        elif type_util.is_wildcard(index):
59
            return index, item
60
        else:
61
            index = _get_index(index)
62
            if index is not None:
63
                return index, item[index]
64
    elif type_util.is_dict(item):
65
        return index, item[index]
66
    raise KeyError(f"Invalid key: '{index}'")
67
68
69
def _get_or_new_item_value(item, key, subkey):
70
    try:
71
        _, value = _get_item_key_and_value(item, key)
72
        if not type_util.is_dict_or_list_or_tuple(value):
73
            raise TypeError
74
    except (IndexError, KeyError, TypeError):
75
        value = _new_item_value(subkey)
76
        _set_item_value(item, key, value)
77
    return value
78
79
80
def _new_item_value(key):
81
    index = _get_index(key)
82
    return {} if index is None else []
83
84
85
def _set_item_value(item, key, value):
86
    index = _get_index(key)
87
    if index is not None:
88
        try:
89
            # overwrite existing index
90
            item[index] = value
91
        except IndexError:
92
            # insert index
93
            item += [None] * (index - len(item))
94
            item.insert(index, value)
95
    elif type_util.is_list(item):
96
        for idx, _item in enumerate(value):
97
            if _item is not None:
98
                item[idx].update({key: _item})
99
    else:
100
        item[key] = value
101
102
103
def get_item(d, keys):
104
    items = get_items(d, keys)
105
    return items[-1] if items else (None, None, None)
106
107
108
def get_items(d, keys):
109
    items = []
110
    item = d
111
    for index, key in enumerate(keys):
112
        try:
113
            if any(items):
114
                parent = items[-1][1]
115
            else:
116
                parent = None
117
            if index < len(keys) - 1:
118
                child = keys[index + 1]
119
            else:
120
                child = None
121
            item_key, item_value = _get_item_key_and_value(item, key, parent, child)
122
            items.append((item, item_key, item_value))
123
            item = item_value
124
        except (IndexError, KeyError):
125
            items.append((None, None, None))
126
            break
127
    return items
128
129
130
def set_item(d, keys, value):
131
    item = d
132
    i = 0
133
    j = len(keys)
134
    while i < j:
135
        key = keys[i]
136
        if i < (j - 1):
137
            item = _get_or_new_item_value(item, key, keys[i + 1])
138
            i += 1
139
            continue
140
        _set_item_value(item, key, value)
141
        break
142