Python cyclomatic complexity in five minutes: radon, and what the numbers mean on real repos
TL;DR: To measure cyclomatic complexity in Python, pip install radon and run radon cc -s -a <path>. Every function gets a score and a grade from A (1 to 5) to F (41 and up).
On Django's own code, 87.0% of 9,242 functions and methods score A and 0.1% score F. On FastAPI, 77.6% of 406 score A. The median in both is 2. The highest scores land on dispatch and translation code, such as Django's schema editor and FastAPI's parameter analysis. Many independent branches, each one a case the framework has to support.
Cyclomatic complexity is one code health marker of several. In repowise's index of 51 popular Python repos, the median code health score is 6.97 out of 10.
The radon runs are on FastAPI at ba5d72b and Django at 6a8248f (November 2026). The code health medians come from repowise's index of 195 public repos with 1,000+ GitHub stars.
Cyclomatic complexity is the number of independent paths through a function. Start at 1, add 1 for every point where the code can go two ways. A function with no branches is 1. A function with one if is 2. It tells you roughly how many test cases you need to cover every path, and it is the oldest code metric still in daily use (Thomas McCabe, 1976).
Below: installing radon, scoring a small function by hand and checking it against the tool, what radon prints on two real codebases, how the grades are spread, what the most complex functions actually look like, and a CI gate with xenon.
How do you measure cyclomatic complexity in Python?
Install radon in a virtualenv. I used radon 6.0.1 on Python 3.13.5.
python -m venv .venv
.venv/bin/pip install radon # .venv\Scripts\pip on Windows
radon cc -s -a src/
cc is the cyclomatic complexity command. -s shows the number next to the grade, -a prints the average at the end.
radon only parses the files with Python's ast module. It never imports or runs your code, so it is safe on any repo.
For a real project you want production code only. radon has two filters:
-i(ignore) takes directory names. radon does not descend into them. Hidden directories are skipped by default.-e(exclude) takes glob patterns matched against file paths, for example-e "*/migrations/*,*_pb2.py".
For FastAPI I ran from the repo root and ignored the test, docs and example folders:
radon cc . -i tests,docs,docs_src,scripts -s -a
fastapi/encoders.py
F 129:0 jsonable_encoder - E (35)
F 59:0 decimal_encoder - A (3)
F 115:0 generate_encoders_by_class_tuples - A (2)
F 53:0 isoformat - A (1)
C 39:4 Color - A (1)
C 48:4 PyExtraColor - A (1)
...
528 blocks (classes, functions, methods) analyzed.
Average complexity: A (3.7443181818181817)
Each line is one block: F function, M method, C class, then line and column, the name, the grade and the score. A class score is roughly the average of its methods, so it is mostly a summary. The useful rows are F and M.
Without -s you get the grade only, which hides the difference between a 21 and a 30.
What is a good cyclomatic complexity score?
radon's grades, from its own source:
- Score 1 to 5, Grade A: low risk, simple block
- Score 6 to 10, Grade B: low risk, well structured and stable block
- Score 11 to 20, Grade C: moderate risk, slightly complex block
- Score 21 to 30, Grade D: more than moderate risk, more complex block
- Score 31 to 40, Grade E: high risk, complex block, alarming
- Score 41 and up, Grade F: very high risk, error-prone, unstable block
McCabe's original suggestion was to split anything above 10, and most tools still put the line around there. So A and B are fine, C deserves a look in review, and D and up are worth a reason.
The labels are strong words for what is really a count of branches, and the real-repo section below shows why.
How does radon count cyclomatic complexity?
I read radon's ComplexityVisitor and checked each rule on small files. Starting from 1, radon adds:
if,elif, ternaryx if c else y: 1 eachfor,async for,while: 1, plus 1 if the loop has anelsetry: 1 perexcept, plus 1 for anelse(finallyadds nothing)and/or: number of operands minus 1 (a and b and cadds 2)- comprehension: 1 per
for, plus 1 perifin it assert: 1 (turn off with--no-assert)match: 1 percase, not countingcase _with,lambda, decorators,return: 0
Two things surprised me. A with block adds nothing, even though a comment in radon's source groups it with if. And nested functions are scored on their own and left out of the parent's number, so a function that defines a closure can look simpler than it reads. --show-closures lists them.
Here is a small function I wrote to check the rules:
def pick_shipping(order, warehouse):
if not order.items: # +1
return None
total = 0
for item in order.items: # +1
if item.qty <= 0 or item.backordered: # +1 if, +1 or
continue
total += item.price * item.qty
try:
with warehouse.lock(): # +0
warehouse.reserve(order)
except TimeoutError: # +1
return "retry"
except KeyError: # +1
return "unknown item"
fragile = [i.sku for i in order.items if i.fragile] # +1 for, +1 if
if total > 100: # +1
tier = "express"
elif fragile: # +1
tier = "careful"
else: # +0
tier = "standard"
return tier
By hand: 1 + 10 = 11. radon agrees:
$ radon cc -s shipping.py
shipping.py
F 1:0 pick_shipping - C (11)
Removing the with line and keeping its body gives the same 11. A plain 27-line function with a loop, a try and a three-way choice is already a C. That is useful calibration before you read real numbers: C is common in ordinary code that handles a few cases.
What do the numbers look like on real repos?
I ran radon on Django's django/ package (ignoring tests, docs, scripts, extras and js_tests) and on FastAPI's fastapi/ package. I counted functions and methods only, the rows radon lists by default, from radon cc -j with a short script:
- Grade A (1 to 5): FastAPI 315 (77.6%), Django 8,040 (87.0%) out of 406 and 9,242
- Grade B (6 to 10): FastAPI 62 (15.3%), Django 801 (8.7%)
- Grade C (11 to 20): FastAPI 17 (4.2%), Django 307 (3.3%)
- Grade D (21 to 30): FastAPI 7 (1.7%), Django 64 (0.7%)
- Grade E (31 to 40): FastAPI 2 (0.5%), Django 18 (0.2%)
- Grade F (41+): FastAPI 3 (0.7%), Django 12 (0.1%)
- Median: 2 in both
- Score exactly 1: 36.5% FastAPI, 43.5% Django
The shape is the same in both: most functions have one or two paths, and a small tail carries most of the branching. 43.5% of Django's functions have no branch at all. Above 10 (C or worse) is 7.1% of FastAPI's functions and 4.3% of Django's.
The average hides that tail. Both repos average an A (3.74 for FastAPI over all 528 blocks, 3.07 for Django over 11,202), and both have F functions. Read the distribution, not the average.
Which functions are the most complex, and is that a problem?
The top five in each, with their length in lines:
Django:
- 99
django/db/backends/base/schema.py BaseDatabaseSchemaEditor._alter_field, 383 lines - 74
django/db/models/base.py ModelBase.__new__, 293 lines - 62
django/core/management/commands/migrate.py Command.handle, 291 lines - 58
django/db/migrations/operations/models.py CreateModel.reduce, 229 lines - 53
django/db/models/sql/compiler.py SQLCompiler.as_sql, 226 lines
FastAPI:
- 54
fastapi/dependencies/utils.py analyze_param, 196 lines - 50
fastapi/telemetry/_asgi.py NativeTelemetry.__call__, 230 lines - 46
fastapi/openapi/utils.py get_openapi_path, 230 lines - 35
fastapi/encoders.py jsonable_encoder, 237 lines - 31
fastapi/routing.py _populate_api_route_state, 163 lines
The ones I read are functions that translate one rich input into many possible outputs. _alter_field takes an old and a new model field and emits the SQL for whatever changed. Read top to bottom, it is a run of independent steps with comments like # Has unique been removed?, # Have they renamed the column?, # Nullability change?. Each step adds a few paths, and none depends much on the one before.
analyze_param has the same shape for FastAPI: is the annotation Annotated, is the default a Depends, is it a FieldInfo, is it a Request. Each branch is a way a user is allowed to declare a parameter.
That is why a high score is a place to look, not a bug report:
- The branches are the spec. Each case is a feature someone uses. Splitting the function into ten helpers moves the branches into ten places, and the total path count does not go down.
- Flat beats nested. Twenty independent
ifblocks in a row read much more easily than five nested four deep, and cyclomatic complexity scores them the same. The nested vs cyclomatic complexity guide shows the same code scored both ways. - Tests carry the weight. Code like this sits behind large test suites that exercise each case. A high score with good tests and a stable history is very different from a high score with no tests in a file that changes every week.
Where the number is worth acting on: a function that is high on cyclomatic complexity, deeply nested, and also changes often or keeps showing up in bug fixes. The score tells you where the paths are. Git history tells you whether those paths are causing trouble.
What do radon mi and radon raw add?
radon mi gives each file a maintainability index from 0 to 100, built from Halstead volume, cyclomatic complexity, source lines and comments. Grades are A above 19, B from 10 to 19, C at 9 or below.
radon mi . -i tests,docs,docs_src,scripts -s
fastapi/applications.py - A (37.49)
fastapi/background.py - A (100.00)
fastapi/cli.py - A (100.00)
fastapi/concurrency.py - A (76.12)
...
fastapi/routing.py - C (0.00)
fastapi/dependencies/utils.py - C (0.00)
FastAPI: 49 files A, 1 B, 2 C. Django: 880 A, 10 B, 20 C out of 910 files. The C files sit at or near 0.00 because the index falls with file size and floors at zero, so it mostly picks out the largest, densest modules (routing.py, models/base.py, sql/query.py). Treat MI as a per-file size and density signal. Use cc for function-level decisions.
radon raw counts lines:
radon raw . -i tests,docs,docs_src,scripts -s
** Total **
LOC: 22937
LLOC: 5803
SLOC: 18979
Comments: 449
Single comments: 294
Multi: 1073
Blank: 2591
LLOC (logical lines, roughly statements) against SLOC (source lines) is the interesting pair here. FastAPI has 18,979 source lines but only 5,803 logical ones, because its public API documents every parameter inline with Annotated[..., Doc("...")], which spreads one signature over many lines (fastapi/applications.py alone has 245 Doc( calls in 4,816 lines). Django's totals are 116,700 SLOC and 85,068 LLOC.
How do you enforce a complexity limit in CI?
xenon wraps radon and exits non-zero when a threshold is crossed. I used xenon 0.9.3. It has three thresholds: -b (max grade for any block), -m (max average grade per module) and -a (max average for the whole codebase).
A strict gate on FastAPI as it is today:
$ xenon --max-absolute B --max-modules A --max-average A -i tests,docs,docs_src,scripts .
ERROR:xenon:block "fastapi/encoders.py:129 jsonable_encoder" has a rank of E
ERROR:xenon:block "fastapi/routing.py:1014 _populate_api_route_state" has a rank of E
ERROR:xenon:block "fastapi/routing.py:2791 app" has a rank of D
...
$ echo $?
1
A gate that starts from where the code is:
$ xenon --max-absolute F --max-modules C --max-average A -i tests,docs,docs_src,scripts .
$ echo $?
0
Tightening -b to E fails on exactly the three F functions. That is how I would adopt it on an existing codebase: set the thresholds to pass today, so the gate only catches new growth, and tighten one grade at a time when someone works in those files. On a new project, --max-absolute C from day one costs very little.
# .github/workflows/complexity.yml (excerpt)
- run: pip install xenon==0.9.3
- run: xenon --max-absolute F --max-modules C --max-average A -i tests,docs .
Two gotchas from these runs. radon cc -nc (shorthand for --min C) prints Average complexity: D (21.27) on FastAPI, because the average only covers the 30 blocks shown. Add --total-average to get the real 3.74. And a xenon module grade is the average of that module's blocks, so one large function in a small file can fail -m on its own.
How does cyclomatic complexity relate to code health?
Cyclomatic complexity measures one thing: how many paths a function has. Code health scores combine it with other markers, such as nesting depth, function length, duplication, test coverage and how often a file changes and gets fixed. The code health markers guide walks through each one.
For a sense of scale: across 195 public repos with 1,000+ GitHub stars, the median code health score is 7.14 out of 10. For the 51 Python repos it is 6.97. The per-language table has the rest.
In repowise, the complexity marker fires on a function with a cyclomatic complexity of 9 or more, at medium severity, high from 15 and critical from 25. A function that is mostly one dispatch on one value, like a long if / elif chain testing the same name, is judged on the decision points outside that dispatch plus its heaviest branch. That is the same reasoning as the _alter_field discussion above, written into the rule.
repowise counts with its own tree-sitter parser, so its numbers will be close to radon's but not identical. If you are working through Python code quality more broadly, the earlier post on Python dead code in 51 popular repos uses the same repos.
How I got these numbers
All radon and xenon numbers are from my own runs on 17 November 2026: radon 6.0.1 and xenon 0.9.3 in a fresh virtualenv on Python 3.13.5, on clones of FastAPI at ba5d72b and Django at 6a8248f. Production code only: for FastAPI the fastapi/ package (ignoring tests, docs, docs_src, scripts), for Django the django/ package (ignoring tests, docs, scripts, extras, js_tests). Neither repo has radon settings in its config, so the runs used radon's defaults.
The grade distribution counts functions and methods from radon cc -j (classes left out, closures folded into their parent as radon does by default). I ran on Windows, and paths are shown with forward slashes.
The code health medians come from repowise's dataset: we analysed 195 of the most-starred public repositories indexed on repowise.dev (1,000+ GitHub stars each, 253,688 production source files, November 2026), each measured at its own latest index. The repowise rule thresholds are from its open-source biomarker code.
FAQ
H
Comments
No comments yet. Start the discussion.