Readable code in practice

Cyclomatic Complexity in Python: Measuring It with mccabe, ruff, pylint and radon

Readable code in practice · · Published 2026-11-19

A square labyrinth drawn entirely with lines of handwritten French text in brown ink, with a spiral at its centre and corridors folding back on themselves
A labyrinth made of handwritten sentences, pen and ink, early 17th century, anonymous. The Metropolitan Museum of Art, CC0.

Some functions are hard to read not because of their layout but because of their shape: a loop inside a condition inside another condition, with early returns scattered along the way. PEP 8 says nothing about this, but most Python linters can measure it. The usual measure is cyclomatic complexity, a number defined by Thomas McCabe in 1976 that counts the independent paths through a piece of code. It is useful, easy to misread, and computed slightly differently by each tool.

What the number counts

McCabe's paper, "A Complexity Measure" (IEEE Transactions on Software Engineering, 1976), treats a function as a control-flow graph and defines its complexity from the number of edges and nodes. For code with a single entry and exit, that comes down to a simple rule: start at 1 and add 1 for every point where execution can take one of two paths. A function with no branches scores 1. Add an if and it scores 2, because there are now two routes through it. The ruff documentation puts it in exactly those words: the complexity "is calculated by adding one to the number of decision points in the function."

The number has a practical reading. It is the minimum number of test cases needed to run every independent path at least once, which is why McCabe proposed it as a guide for testing as well as for design. A function scoring 12 needs at least twelve tests to exercise its branches; most such functions have far fewer, and that gap is where bugs live.

What it does not measure is just as important. A long, flat sequence of statements scores 1. Deep nesting and shallow chains score the same if they contain the same number of branches. Poor names, clever one-liners and hidden state are invisible to it. It is one signal of readability among several, alongside the habits described in our guide to readable Python code.

One function, four tools

Here is a shipping-cost function of a kind found in many codebases. It has grown one rule at a time:

def shipping_cost(order):
    if not order.items:
        return 0
    weight = 0
    for item in order.items:
        if item.fragile:
            weight += item.weight * 1.2
        else:
            weight += item.weight
    if order.country == "FR":
        if weight < 2:
            cost = 5
        elif weight < 10:
            cost = 9
        else:
            cost = 15
    elif order.country in ("BE", "DE", "ES", "IT"):
        if weight < 2:
            cost = 8
        elif weight < 10:
            cost = 14
        else:
            cost = 22
    else:
        cost = 30 if weight < 10 else 45
    if order.express and order.country == "FR":
        cost *= 2
    if order.coupon and order.total > 100:
        cost = 0
    return cost

Counting by hand: one for, and ten if or elif tests, gives eleven decision points, so a complexity of 12. The tools agree, with one exception:

$ ruff check --select C901 shipping.py
C901 `shipping_cost` is too complex (12 > 10)

$ flake8 --max-complexity 10 shipping.py
shipping.py:1:1: C901 'shipping_cost' is too complex (12)

$ pylint --load-plugins=pylint.extensions.mccabe shipping.py
shipping.py:1:0: R1260: 'shipping_cost' is too complex. The McCabe rating is 12 (too-complex)
shipping.py:1:0: R0912: Too many branches (15/12) (too-many-branches)

$ radon cc -s shipping.py
    F 1:0 shipping_cost - C (15)

radon reports 15 because it also counts the conditional expression (30 if weight < 10 else 45) and each and as decision points. Both are real branches at run time, so radon's count is arguably the more faithful one; mccabe ignores them. Pylint's separate too-many-branches check gives yet another figure, 15, because it counts branches (including else) rather than decision points. None of these is wrong. They are different rulers, so compare scores only between runs of the same tool.

Turning the check on

flake8 bundles the mccabe plugin, but it reports nothing until you set max-complexity, as our comparison of flake8 and pylint notes. Ruff's C901 rule belongs to the C90 group, which is not in its default rule selection, so you add it explicitly. Pylint ships the check as an optional extension, pylint.extensions.mccabe, while its design checks, such as too-many-branches, are on by default. In pyproject.toml:

[tool.ruff.lint]
extend-select = ["C90"]

[tool.ruff.lint.mccabe]
max-complexity = 10

[tool.pylint.main]
load-plugins = ["pylint.extensions.mccabe"]

[tool.pylint.design]
max-complexity = 10

For flake8, which reads setup.cfg, tox.ini or .flake8, the equivalent is max-complexity = 10 in the [flake8] section. Ruff's own default for max-complexity is 10, as ruff config lint.mccabe.max-complexity reports. The rule's setup in ruff is covered in more detail in our ruff guide.

Which limit?

McCabe suggested 10 as an upper bound in his original paper, and it remains the usual default. radon's grades give another scale: A for 1 to 5, B for 6 to 10, C for 11 to 20, then D, E and F up to 41 and above. A sensible policy for a team:

Bringing a function back under the limit

The aim is a function whose structure a reader can hold in their head, not a lower number at any cost. Three techniques do most of the work on the example above.

  1. Extract named steps. The weight loop becomes parcel_weight(items), a one-line sum(). Each extracted function can be read, named and tested on its own.
  2. Replace branch ladders with data. The two nested if/elif blocks differ only in their numbers. A dictionary of rates per zone ({"FR": (5, 9, 15), "EU": (8, 14, 22)}) and a single function that picks the band removes one whole ladder.
  3. Return early on special cases. Handling the empty order and the coupon at the top removes them from the rest of the logic.

After the refactoring, the same behaviour is spread over four functions. mccabe scores them 1, 3, 4 and 4; radon's highest grade is B (6). The total number of decisions has hardly changed, because the business rules are the same; what has changed is that no single function contains them all. The refactored version is also easier to test, since the rate table can be checked separately from the zone logic.

Two moves lower the score without helping anyone. Packing conditions into a long boolean expression satisfies mccabe, which does not count and and or, but not radon or a human reader. Moving branches into a dictionary of lambdas can hide control flow rather than simplify it. If the refactored code is harder to follow than the original, keep the original and document the exception.

Sources