In this lesson, you will learn how to measure the structural complexity of your functions by calculating Cyclomatic Complexity to identify code that has become too difficult to test or maintain.
Understanding Cyclomatic Complexity
Cyclomatic Complexity is a quantitative measure of the number of linearly independent paths through your source code. Simply put: every time your code makes a decision (like an if, while, or for loop), it branches. The more branches you have, the higher the complexity, and the harder it becomes to reason about the function's behavior.
How to Calculate It
The formula is straightforward: Complexity = Number of Decision Points + 1.
Consider this function:
def process_order(price: float, discount: float) -> float:
final_price = price
# Decision point 1: if
if discount > 0:
final_price -= discount
# Decision point 2: if
if final_price < 0:
return 0.0
return final_price
In the example above, we have two if statements. Plugging this into our formula: 2 decision points + 1 = 3. This function has a Cyclomatic Complexity of 3.
Why It Matters for Quality
A complexity score of 1–5 is generally considered simple and easy to maintain. Once a function crosses 10, it often becomes a "God function"—a large block of logic that is highly prone to bugs and difficult to unit test because you would need to write a vast number of test cases to cover every possible execution path.
If your static analysis tools (like Ruff or specialized complexity checkers) flag a high complexity score, it is a clear signal to refactor. You can reduce complexity by extracting nested logic into smaller, helper functions. By breaking a function with a complexity of 12 into three smaller functions with a complexity of 4 each, you make your codebase significantly more readable and easier to verify with your existing mypy type-checking standards.
Key Takeaway: Cyclomatic Complexity quantifies your code's branching logic, and keeping this score low ensures your functions remain modular, testable, and maintainable.