radon

repository·master·Indexed 24 days ago

https://github.com/rubik/radon

A Python tool for computing source code metrics, including McCabe's cyclomatic complexity, Halstead metrics, the Maintainability Index, and raw metrics such as SLOC, comments, and blank lines. It provides a command-line interface, a programmatic API with three abstraction layers (Visitors, Helper Functions, and Harvesters), and a plugin for flake8.

Tokens
8.9K
Snippets
9
Records
54
Agent score
71%

What's inside radon

  1. Overview of Radon metrics

    master

    Radon is a Python tool used to compute various code metrics. It supports the following types of analysis:

    • Raw metrics: Includes SLOC (Source Lines of Code), comment lines, blank lines, and more.
    • Cyclomatic Complexity: Implements McCabe's Complexity metric.
    • Halstead metrics: Provides a full suite of Halstead complexity metrics.
    • Maintainability Index: Implements the metric used by Visual Studio to assess code maintainability.
  2. Understand Cyclomatic Complexity in Radon

    master

    Cyclomatic Complexity (also called the McCabe number) represents the number of linearly independent paths through a block of code. It is calculated as the number of decisions in a code block plus 1. Radon computes this by analyzing the Python AST (Abstract Syntax Tree).

    Common Python constructs and their effects on Cyclomatic Complexity (CC):

    ConstructEffect on CCReasoning
    if+1Single decision
    elif+1Adds another decision
    else+0Decision is handled by the if
    case pattern+1Single decision
    case _+0Decision is handled by the case pattern
    for+1Decision at the start of the loop
    while+1Decision at the while statement
    except+1Each branch adds a new conditional path
    finally+0Unconditionally executed
    with+1Corresponds roughly to a try/except block
    assert+1Internally behaves like a conditional
    Comprehension+1List/set/dict comprehensions or generator expressions act like for loops
    Boolean Operator+1Every and or or adds a decision point
  3. Understand Radon's programmatic API layers

    master

    Radon's API is organized into three hierarchical layers depending on the level of abstraction required:

    1. Visitors (Lowest Level): Classes used to build an AST from code and extract basic metrics. Use radon.visitors.ComplexityVisitor for cyclomatic complexity and radon.visitors.HalsteadVisitor for Halstead metrics.
    2. Helper Functions (Middle Level): High-level functions residing in specific modules for common tasks:
      • radon.complexity: For cyclomatic complexity analysis.
      • radon.metrics: For Halstead metrics and the Maintainability Index (MI).
      • radon.raw: For raw metrics like SLOC, LLOC, and LOC.
    3. Harvesters (Highest Level): Implements the business logic used by the Radon CLI. Harvesters take a radon.cli.Config object and a list of paths to analyze, and can export results to various formats (e.g., JSON or XML for cyclomatic complexity).
  4. How to use Radon

    master

    Radon can be integrated into your workflow in two ways:

    1. Command Line Interface (CLI): Run Radon directly from your terminal to analyze files or directories.
    2. Programmatic API: Import Radon into your Python scripts to use its metrics calculation functions directly in your code.
  5. Understand Maintainability Index (MI)

    master

    The Maintainability Index (MI) measures how easy it is to support and change source code. It is a factored formula involving SLOC (Source Lines of Code), Cyclomatic Complexity, and Halstead volume.

    Radon uses a specific derivative of the MI formula, which is a hybrid of the SEI and Visual Studio implementations:

    MI = max [ 0, 100 * (171 - 5.2 * ln(V) - 0.23 * G - 16.2 * ln(L) + 50 * sin(sqrt(2.4 * C))) / 171 ]

    Where:

    • V: Halstead Volume
    • G: Total Cyclomatic Complexity
    • L: Number of Source Lines of Code (SLOC)
    • C: Percent of comment lines (converted to radians)

    Note: Maintainability Index is considered an experimental metric and should be used with caution compared to other metrics.

  6. Install Radon via Pip

    master

    You can install Radon using pip. If you are running Python versions earlier than 3.11 and wish to configure Radon using a pyproject.toml file, you must install the toml extra dependency.

    To install the standard version:

    $ pip install radon

    To install with pyproject.toml support (for Python < 3.11):

    $ pip install radon[toml]
    $ pip install radon
  7. Use Harvesters to replicate CLI behavior

    master

    To use Radon's full CLI capabilities programmatically, use a Harvester (or specific harvesters like CCHarvester, RawHarvester, or MIHarvester).

    1. Create a radon.cli.Config object containing your desired configuration.
    2. Instantiate a Harvester with the config.
    3. Pass a list of paths to the harvester to analyze.
    4. Use the harvester's methods to export results to formats like JSON or XML.
  8. Analyze Jupyter Notebooks with Radon

    master

    Radon can inspect code metrics within .ipynb files. To use this feature, you must first install the nbformat package:

    $ pip install nbformat

    When running Radon commands, use the following flags:

    • --include-ipynb: Enables scanning of Jupyter notebooks.
    • --ipynb-cells: Enables reporting of metrics for individual cells.

    Note: Any % macros in the notebook will be ignored in the metrics.

    Example command to run raw metrics on a notebook:

    $ radon raw --include-ipynb --ipynb-cells .
    $ radon raw --include-ipynb --ipynb-cells .
  9. Handle Unicode characters with RADONFILESENCODING

    master
    On systems where the default encoding is not UTF-8 (such as Windows), you must set the RADONFILESENCODING environment variable to UTF-8 if your Python files contain Unicode characters to ensure they are analyzed correctly.
  10. Use Radon with Jupyter Notebooks

    master

    Radon can analyze .ipynb files to inspect code metrics within Python cells. Any % macros are ignored during analysis.

    Requirements: Install the nbformat package: pip install nbformat.

    Usage:

    • Use the --include-ipynb flag to enable scanning of Jupyter notebooks.
    • Use the --ipynb-cells flag to report on individual cells within the notebooks.
  11. Understand the Function and Class data structures

    master

    Radon uses specialized namedtuple subclasses to represent code blocks. These objects provide metadata about the location and complexity of functions and classes.

    Function Object

    Represents a function or method block.

    • name: The identifier of the function.
    • fullname: The qualified name (e.g., ClassName.method_name for methods, or just name for functions).
    • letter: 'M' if it is a method, 'F' if it is a function.
    • complexity: The cyclomatic complexity of the function.
    • lineno, col_offset, endline: Location information.
    • is_method (bool): Indicates if the function is a method.
    • classname: The name of the class this method belongs to.
    • closures: A list of functions defined within this function.

    Class Object

    Represents a class block.

    • name: The identifier of the class.
    • fullname: The name of the class.
    • letter: Always 'C'.
    • complexity: The average complexity of the class (average complexity of its methods plus one).
    • methods: A list of Function objects representing the class's methods.
    • inner_classes: A list of Class objects defined within this class.
    • lineno, col_offset, endline: Location information.