liveBook · Manning

Complexity

As explained in Practices of the Python Pro

A complexity measurement is a quantitative assessment of the structural or computational complexity of software or an algorithm.

A complexity metric quantitatively assesses how difficult code is to understand and maintain. It offers a stronger signal than subjective confusion or physical size when deciding what to refactor. section 9.1.3 section 9.4

Cyclomatic complexity focuses on execution paths through a function:

  • Count paths shaped by conditional expressions and loops. section 9.1.3
  • Represent function starts, conditions, loops, loop ends, and returns as control-flow nodes. section 9.1.3
  • Use score trends over time, rather than treating one specific score as decisive. section 9.1.3
  • Prioritize highly complex code when investing refactoring effort. section 9.1.3

Checking a sentence for long words

The function accepts either a string or a list, normalizes strings, loops through the words, checks a length condition, and returns early when it finds a long word. These branches and loop paths make it useful for illustrating cyclomatic complexity. section 9.1.3

Listing 9.1. A function with conditionals and a loop
def has_long_words(sentence):
    if isinstance(sentence, str):          #1
        sentence = sentence.split(' ')

    for word in sentence:                  #2
        if len(word) > 10:                 #3
            return True

    return False                           #4

Inspect the short Python function and trace how normalization, iteration, conditional checking, and returns create execution paths. section 9.1.3

How Practices of the Python Pro covers it

How deep it goes
Explains cyclomatic complexity through execution paths, control-flow graphs, conditionals, loops, nodes, and edges.
Examples
Uses a Python sentence-checking function containing input normalization, a loop, a length condition, and early returns.
What you can do after
Diagnose/debug with it: identify high-complexity code and prioritize refactoring by tracking scores over time.
How it connects
Connects complexity metrics to refactoring, maintainability, separate concerns, control flow, conditionals, and loops.

Also explained in

Compare how 13 books explain complexity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Practices of the Python Pro. The section links point to the parts of the book it draws on.