completely_empty.completely_empty()   D
last analyzed

Complexity

Conditions 13

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 13
eloc 26
nop 1
dl 0
loc 34
rs 4.2
c 0
b 0
f 0

How to fix   Complexity   

Complexity

Complex classes like completely_empty.completely_empty() 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
import collections
2
3
4
def completely_empty(val):
5
    if type(val) == str:
6
        if val == '':
7
            return True
8
        else:
9
            return False
10
11
    if type(val) == list:
12
        if len(val) == 0:
13
            return True
14
        else:
15
            return all([completely_empty(i) for i in val])
16
17
    if type(val) == dict:
18
        if len(val) == 0:
19
            return True
20
        elif len(val.keys()) == 1 and '' in val:
21
            return True
22
        return False
23
24
    if type(val) == tuple:
25
        return completely_empty(list(val))
26
27
    try:
28
        val.__getitem__(0)
29
    except IndexError:
30
        return True
31
    except AttributeError:
32
        pass
33
34
    if isinstance(val, collections.Iterable):
35
        return all([completely_empty(i) for i in val])
36
    else:
37
        return False
38
39
40
if __name__ == '__main__':
41
    # These "asserts" using only for self-checking
42
    # and not necessary for auto-testing
43
    assert completely_empty([]) == True, "First"
44
    assert completely_empty([1]) == False, "Second"
45
    assert completely_empty([[]]) == True, "Third"
46
    assert completely_empty([[], []]) == True, "Forth"
47
    assert completely_empty([[[]]]) == True, "Fifth"
48
    assert completely_empty([[], [1]]) == False, "Sixth"
49
    assert completely_empty([0]) == False, "[0]"
50
    assert completely_empty(['']) == True
51
    assert completely_empty([[], [{'': 'No WAY'}]]) == True
52
    print('Done')
53