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