Radon

6.0.1 · active · verified Thu Apr 09

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

Install

Imports

Quickstart

This quickstart demonstrates how to use `radon.complexity.cc_visit` to programmatically analyze Python code for cyclomatic complexity. It shows how to pass a string of code and iterate through the detected code blocks, printing their name, complexity score, and rank.

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}")

view raw JSON →