Radon
Radon is a Python tool that computes various metrics from the source code, including McCabe's cyclomatic complexity, raw metrics (SLOC, comment lines, blank lines), Halstead metrics, and the Maintainability Index. It can be used via the command line or programmatically through its API. The current version is 6.0.1, released in March 2023, and it maintains a consistent release cycle with several minor and patch updates annually.
Warnings
- breaking Python 2.6 is no longer supported since Radon version 2.0.0. Projects still using Python 2.6 will need to use an older Radon version (<= 1.5.0) or upgrade their Python environment.
- gotcha On Windows, if your Python files contain Unicode characters and your system's default encoding is not UTF-8, Radon might encounter encoding issues.
- breaking Radon's total complexity calculation for classes was fixed in version 3.0.0, which might lead to different (more accurate) results compared to previous versions.
- breaking Support for `flake8 < 3.x` was dropped in version 5.0.1, leading to the removal of the `flake8-polyfill` dependency. This was temporarily added back in 4.5.2 and then definitively removed.
Install
-
pip install radon -
pip install radon[toml] -
pip install nbformat
Imports
- cc_visit
from radon.complexity import cc_visit
- mi_visit
from radon.metrics import mi_visit
- analyze
from radon.raw import analyze
- h_visit
from radon.halstead import h_visit
Quickstart
from radon.complexity import cc_visit
def my_complex_function(x, y):
if x > 0 and y < 10:
return x * y
elif x < 0 or y > 20:
return x + y
else:
return 0
code = """
def example_function(a, b):
if a > 0:
if b < 0:
return a - b
else:
return a + b
else:
return 0
"""
# Analyze a string of code
complexity_blocks = cc_visit(code)
for block in complexity_blocks:
print(f"Function: {block.name}, Complexity: {block.real_cc}, Rank: {block.rank}")
# Or analyze a function object directly (Radon works on AST nodes, so you'd typically parse a file or string first)
# For a direct function object like my_complex_function, you would need to parse its source:
import inspect
function_code = inspect.getsource(my_complex_function)
complexity_for_func_obj = cc_visit(function_code)
for block in complexity_for_func_obj:
print(f"Function: {block.name}, Complexity: {block.real_cc}, Rank: {block.rank}")