haive.core.utils.debugkit.analysis.complexityΒΆ

Advanced complexity analysis for Python functions and modules.

This module provides comprehensive code complexity analysis including: - Cyclomatic complexity (traditional control flow complexity) - Cognitive complexity (human-perceived complexity) - Halstead metrics (algorithmic complexity) - Maintainability index calculation - Nesting depth analysis - Custom complexity scoring and grading

The complexity analyzer helps identify code that may be difficult to maintain, test, or understand, providing actionable recommendations for improvement.

ClassesΒΆ

ComplexityAnalyzer

Advanced code complexity analyzer.

ComplexityGrade

Complexity grade classifications.

ComplexityHotspot

A specific location in code with high complexity.

ComplexityMetrics

Comprehensive complexity metrics for a code unit.

ComplexityReport

Complete complexity analysis report for a function.

ComplexityType

Types of complexity measurements.

ManualComplexityAnalyzer

Manual complexity analyzer using AST traversal.

Module ContentsΒΆ

class haive.core.utils.debugkit.analysis.complexity.ComplexityAnalyzer(use_radon=HAS_RADON, use_mccabe=HAS_MCCABE, strict_thresholds=False, custom_thresholds=None)[source]ΒΆ

Advanced code complexity analyzer.

This class provides comprehensive complexity analysis for Python functions and modules using multiple complexity metrics and analysis techniques.

The analyzer integrates with external tools when available (radon, mccabe) and provides fallback implementations for core functionality.

use_radonΒΆ

Whether to use radon for enhanced metrics

use_mccabeΒΆ

Whether to use mccabe for cyclomatic complexity

strict_thresholdsΒΆ

Whether to use strict complexity thresholds

custom_thresholdsΒΆ

Custom complexity thresholds

Examples

Basic complexity analysis:

analyzer = ComplexityAnalyzer()

def complex_function(data, config=None):
    if not data:
        return None

    result = []
    for item in data:
        if config and 'filter' in config:
            if item.get('type') == config['filter']:
                if item.get('status') == 'active':
                    result.append(process_item(item))
    return result

report = analyzer.analyze_function(complex_function)
print(f"Complexity grade: {report.complexity_grade}")
print(f"Suggestions: {len(report.refactoring_suggestions)}")

Custom thresholds:

analyzer = ComplexityAnalyzer(
    strict_thresholds=True,
    custom_thresholds={
        'cyclomatic': {'low': 3, 'medium': 6, 'high': 10},
        'nesting': {'low': 2, 'medium': 3, 'high': 4}
    }
)

Initialize the complexity analyzer.

Parameters:
  • use_radon (bool) – Whether to use radon for enhanced complexity metrics

  • use_mccabe (bool) – Whether to use mccabe for cyclomatic complexity

  • strict_thresholds (bool) – Whether to use strict complexity thresholds

  • custom_thresholds (dict[str, dict[str, int]] | None) – Custom thresholds for complexity metrics

analyze_function(func)[source]ΒΆ

Perform comprehensive complexity analysis on a function.

Analyzes all aspects of function complexity including control flow, cognitive load, structural complexity, and maintainability metrics.

Parameters:

func (collections.abc.Callable[Ellipsis, Any]) – The function to analyze

Returns:

Complete complexity analysis results

Return type:

ComplexityReport

Raises:
  • ValueError – If the function cannot be analyzed

  • TypeError – If the input is not a callable

Examples

Analyze function complexity:

def nested_function(items, config):
    result = {}
    for item in items:
        if item.get('active'):
            category = item.get('category', 'default')
            if category not in result:
                result[category] = []

            if config.get('validate', True):
                if validate_item(item):
                    result[category].append(item)
            else:
                result[category].append(item)
    return result

report = analyzer.analyze_function(nested_function)

# Check if refactoring is needed
if report.needs_refactoring():
    print("Function should be refactored")
    for suggestion in report.refactoring_suggestions:
        print(f"- {suggestion}")
class haive.core.utils.debugkit.analysis.complexity.ComplexityGrade[source]ΒΆ

Bases: str, enum.Enum

Complexity grade classifications.

AΒΆ

Excellent - Low complexity, highly maintainable

BΒΆ

Good - Moderate complexity, maintainable

CΒΆ

Fair - Some complexity, may need refactoring

DΒΆ

Poor - High complexity, should be refactored

FΒΆ

Critical - Very high complexity, urgent refactoring needed

Initialize self. See help(type(self)) for accurate signature.

class haive.core.utils.debugkit.analysis.complexity.ComplexityHotspot[source]ΒΆ

A specific location in code with high complexity.

typeΒΆ

Type of complexity hotspot

line_numberΒΆ

Line number where hotspot occurs

descriptionΒΆ

Human-readable description

severityΒΆ

Severity level (low/medium/high/critical)

suggestionΒΆ

Specific suggestion for improvement

contextΒΆ

Additional context about the hotspot

Examples

Process hotspots:

for hotspot in complexity_report.hotspots:
    print(f"Line {hotspot.line_number}: {hotspot.description}")
    print(f"Suggestion: {hotspot.suggestion}")
class haive.core.utils.debugkit.analysis.complexity.ComplexityMetrics[source]ΒΆ

Comprehensive complexity metrics for a code unit.

This class contains all complexity measurements for a function, providing both traditional and advanced complexity metrics.

cyclomatic_complexityΒΆ

Traditional cyclomatic complexity

cognitive_complexityΒΆ

Human-perceived complexity

halstead_metricsΒΆ

Dictionary of Halstead metrics

maintainability_indexΒΆ

Maintainability index (0-100)

lines_of_codeΒΆ

Total lines including comments and blanks

logical_lines_of_codeΒΆ

Lines containing actual code

comment_linesΒΆ

Number of comment lines

blank_linesΒΆ

Number of blank lines

comment_ratioΒΆ

Ratio of comments to code lines

nesting_depthΒΆ

Maximum nesting depth

parameter_countΒΆ

Number of function parameters

return_countΒΆ

Number of return statements

branch_countΒΆ

Number of conditional branches

loop_countΒΆ

Number of loops

function_callsΒΆ

Number of function calls

unique_operatorsΒΆ

Number of unique operators (Halstead)

unique_operandsΒΆ

Number of unique operands (Halstead)

total_operatorsΒΆ

Total number of operators (Halstead)

total_operandsΒΆ

Total number of operands (Halstead)

Examples

Access specific metrics:

metrics = complexity_analyzer.analyze_function(my_func).metrics

print(f"Cyclomatic complexity: {metrics.cyclomatic_complexity}")
print(f"Cognitive complexity: {metrics.cognitive_complexity}")
print(f"Maintainability index: {metrics.maintainability_index}")
print(f"Comment ratio: {metrics.comment_ratio:.1%}")

Check thresholds:

if metrics.cyclomatic_complexity > 10:
    print("Function is too complex")

if metrics.nesting_depth > 4:
    print("Function has excessive nesting")
get_complexity_breakdown()[source]ΒΆ

Get detailed breakdown of complexity contributors.

Returns:

Breakdown of complexity scores by type

Return type:

Dict[str, float]

get_overall_complexity_score()[source]ΒΆ

Calculate overall complexity score combining all metrics.

Returns:

Overall complexity score (0-100, higher is more complex)

Return type:

float

Examples

Get overall complexity:

score = metrics.get_overall_complexity_score()
if score > 75:
    print("Function is highly complex")
class haive.core.utils.debugkit.analysis.complexity.ComplexityReport[source]ΒΆ

Complete complexity analysis report for a function.

This class contains comprehensive complexity analysis results including metrics, grading, recommendations, and specific hotspots that need attention.

function_nameΒΆ

Name of the analyzed function

module_nameΒΆ

Module containing the function

metricsΒΆ

Detailed complexity metrics

complexity_gradeΒΆ

Overall complexity grade (A-F)

grade_breakdownΒΆ

Grade breakdown by complexity type

refactoring_suggestionsΒΆ

List of specific refactoring suggestions

hotspotsΒΆ

List of complexity hotspots in the code

risk_scoreΒΆ

Overall risk score (0-100, higher is riskier)

maintainability_scoreΒΆ

Maintainability score (0-100, higher is better)

testability_scoreΒΆ

How easy the function is to test (0-100)

analysis_timestampΒΆ

When analysis was performed

thresholds_exceededΒΆ

Which complexity thresholds were exceeded

Examples

Review analysis results:

report = complexity_analyzer.analyze_function(my_function)

print(f"Overall grade: {report.complexity_grade}")
print(f"Risk score: {report.risk_score}")

if report.risk_score > 75:
    print("High risk function - needs refactoring")
    for suggestion in report.refactoring_suggestions:
        print(f"- {suggestion}")

# Review specific hotspots
for hotspot in report.hotspots:
    if hotspot.severity == "critical":
        print(f"Critical issue at line {hotspot.line_number}")
get_summary()[source]ΒΆ

Get summary of complexity analysis.

Returns:

Summary containing key metrics and assessments

Return type:

Dict[str, Any]

needs_refactoring()[source]ΒΆ

Determine if function needs refactoring based on complexity.

Returns:

True if refactoring is recommended

Return type:

bool

class haive.core.utils.debugkit.analysis.complexity.ComplexityType[source]ΒΆ

Bases: str, enum.Enum

Types of complexity measurements.

CYCLOMATICΒΆ

Traditional cyclomatic complexity (control flow)

COGNITIVEΒΆ

Cognitive complexity (human perception)

HALSTEADΒΆ

Halstead complexity (algorithmic)

NESTINGΒΆ

Nesting depth complexity

PARAMETERΒΆ

Parameter count complexity

LENGTHΒΆ

Code length complexity

Initialize self. See help(type(self)) for accurate signature.

class haive.core.utils.debugkit.analysis.complexity.ManualComplexityAnalyzer[source]ΒΆ

Bases: ast.NodeVisitor

Manual complexity analyzer using AST traversal.

Initialize the analyzer.

visit_BoolOp(node)[source]ΒΆ

Visit boolean operations for cognitive complexity.

Parameters:

node (ast.BoolOp)

Return type:

None

visit_Call(node)[source]ΒΆ

Visit function calls.

Parameters:

node (ast.Call)

Return type:

None

visit_For(node)[source]ΒΆ

Visit for loops for complexity calculation.

Parameters:

node (ast.For)

Return type:

None

visit_FunctionDef(node)[source]ΒΆ

Visit function definition to count parameters.

Parameters:

node (ast.FunctionDef)

Return type:

None

visit_If(node)[source]ΒΆ

Visit if statements for complexity calculation.

Parameters:

node (ast.If)

Return type:

None

visit_Return(node)[source]ΒΆ

Visit return statements.

Parameters:

node (ast.Return)

Return type:

None

visit_Try(node)[source]ΒΆ

Visit try statements for complexity calculation.

Parameters:

node (ast.Try)

Return type:

None

visit_While(node)[source]ΒΆ

Visit while loops for complexity calculation.

Parameters:

node (ast.While)

Return type:

None