liveBook · Manning

Cyclomatic complexity

As explained in Practices of the Python Pro

Cyclomatic complexity is a software metric that measures the number of linearly independent paths through a program's control-flow graph.

Cyclomatic complexity measures how many execution paths pass through a function or method. Conditionals and loops increase the number of paths, making code harder to read and maintain. section 9.1.3

Use the score mainly as a trend: rising complexity highlights code worth refactoring, while the exact number is less useful by itself. A control-flow graph lets you count paths manually by identifying starts, conditions, loops, loop ends, and returns. section 9.1.3

A function with several paths

The has_long_words function accepts a string or word list, conditionally splits strings, loops through words, and returns early when it finds a long word. Its control flow demonstrates how conditionals, loops, and returns contribute to complexity. section 9.1.3

Reduce excessive complexity by changing how behavior is organized:

  • Extract repeated choices into configuration, such as mapping Accept header values to response formats; this can return an endpoint to complexity 1. section 9.2.1
  • Separate decisions from actions by extracting response-formatting functions and a function that selects the appropriate formatter. section 9.2.2
  • Measure automatically with tools such as SonarQube or Radon, including during development through editor integration. section 9.2
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 a short Python function whose conditional, loop, early return, and final return make control-flow paths concrete. section 9.1.3

How Practices of the Python Pro covers it

How deep it goes
Defines execution paths, sketches control-flow graph counting, and demonstrates refactoring, while deferring formal mathematical analysis.
Examples
Uses Python functions for long-word detection, GitHub-star importing, and response formatting with JSON, XML, and configuration mappings.
What you can do after
Diagnose/debug with it by spotting path-heavy functions, measuring them manually or with Radon and SonarQube, and reducing branching through refactoring.
How it connects
Connects control-flow graphs, code complexity, refactoring, configuration, separation of concerns, and Halstead complexity.

Also explained in

Compare how 5 books explain cyclomatic 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.