Complex code hard to maintain Low

Complex code can be difficult to read and hard to maintain. For example, using three parameters in a single statement while slicing data, and comprehension with more than two subexpressions, can both be hard to understand.

Detector ID
python/code-readability@v1.0
Category
Common Weakness Enumeration (CWE) external icon
-

Noncompliant example

1def avoid_complex_comprehension_noncompliant():
2    text = [['bar', 'pie', 'line'],
3            ['Rome', 'Madrid', 'Houston'],
4            ['aa', 'bb', 'cc', 'dd']]
5    # Noncompliant: list comprehensions with more than two control
6    # sub expressions are hard to read and maintain.
7    text_3 = [y.upper() for x in text if len(x) == 3 for y in x
8              if y.startswith('f')]

Compliant example

1def avoid_complex_comprehension_compliant():
2    text = [['bar', 'pie', 'line'],
3            ['Rome', 'Madrid', 'Houston'],
4            ['aa', 'bb', 'cc', 'dd']]
5    text_1 = []
6    # Compliant: easy to read and maintain.
7    for x in text:
8        if len(x) > 3:
9            for y in x:
10                text_1.append(y)