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




