Complexipy

5.2.0 · active · verified Thu Apr 16

Complexipy is an extremely fast Python library, written in Rust, designed to calculate the cognitive complexity of Python files. Unlike cyclomatic complexity, it focuses on measuring how difficult code is for humans to read and understand, identifying hard-to-maintain sections. It operates as both a command-line interface (CLI) tool and a Python API, facilitating integration into development workflows, CI/CD pipelines, and pre-commit hooks. The current version is 5.2.0, with an active release cadence, frequently adding new features and improvements.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use `complexipy` both by analyzing a Python code string directly and by analyzing a Python file on disk. It imports `file_complexity` and `code_complexity` to get detailed cognitive complexity metrics for functions within the given code.

import os
from complexipy import file_complexity, code_complexity

# Example 1: Analyze a Python string
snippet = """
def calculate_discount(price, quantity, is_member):
    if is_member:
        if quantity > 10:
            return price * quantity * 0.8 # 20% discount
        else:
            return price * quantity * 0.9 # 10% discount
    else:
        return price * quantity
"""

print("\n--- Analyzing code snippet ---")
result_code = code_complexity(snippet)
print(f"Overall snippet complexity: {result_code.complexity}")
for func in result_code.functions:
    print(f"  Function '{func.name}': Complexity {func.complexity}, Line {func.line_start}-{func.line_end}")

# Example 2: Analyze a temporary Python file
file_content = """
def process_data(data):
    if data.get('status') == 'active':
        for item in data.get('items', []):
            if item.get('value', 0) > 100:
                print(f"Processing high-value item: {item['id']}")
            else:
                print(f"Processing regular item: {item['id']}")
    elif data.get('status') == 'pending':
        print("Data pending, skipping processing.")
    else:
        print("Unknown data status.")
"""

file_path = "example_module.py"
with open(file_path, "w") as f:
    f.write(file_content)

print(f"\n--- Analyzing file: {file_path} ---")
result_file = file_complexity(file_path)
print(f"File complexity: {result_file.complexity}")
for func in result_file.functions:
    print(f"  Function '{func.name}': Complexity {func.complexity}, Line {func.line_start}-{func.line_end}")

# Clean up temporary file
os.remove(file_path)

view raw JSON →