Passed
Push — master ( 68a360...546f3a )
by Fabio
03:54
created

benedict.utils.utility_util.clean()   C

Complexity

Conditions 10

Size

Total Lines 10
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 10
dl 0
loc 10
rs 5.9999
c 0
b 0
f 0
cc 10
nop 4

How to fix   Complexity   

Complexity

Complex classes like benedict.utils.utility_util.clean() 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 six import string_types
4
5
import copy
6
import json
7
8
9
def clean(d, strings=True, dicts=True, lists=True):
10
    keys = list(d.keys())
11
    for key in keys:
12
        value = d.get(key, None)
13
        if not value:
14
            if value is None or \
15
                    strings and isinstance(value, string_types) or \
16
                    dicts and isinstance(value, dict) or \
17
                    lists and isinstance(value, (list, tuple, )):
18
                del d[key]
19
20
21
def clone(d):
22
    return copy.deepcopy(d)
23
24
25
def dump(data):
26
    def encoder(obj):
27
        json_types = (bool, dict, float, int, list, tuple, ) + string_types
28
        if not isinstance(obj, json_types):
29
            return str(obj)
30
    return json.dumps(data, indent=4, sort_keys=True, default=encoder)
31
32
33
def filter(d, predicate):
34
    f = {}
35
    keys = d.keys()
36
    for key in keys:
37
        val = d.get(key, None)
38
        if predicate(key, val):
39
            f[key] = val
40
    return f
41
42
43
def merge(d, other):
44
    for key, value in other.copy().items():
45
        src = d.get(key, None)
46
        if isinstance(src, dict) and isinstance(value, dict):
47
            merge(src, value)
48
        else:
49
            d[key] = value
50
    return d
51