function_call_analyzer

Function Call Analyzer Module.

This module provides functionality to analyze function definitions and calls in Python code using LibCST. It helps identify unused functions and analyze function call patterns in a codebase.

Example

>>> from haive.tools.toolkits.dev.python.cst_toolkit.visitors.function_call_analyzer import analyze_function_calls
>>> analyze_function_calls("/path/to/file.py")
Unused Functions: ['initialize_config', 'cleanup_resources']

Classes

FunctionCallAnalyzer

Tracks function definitions and calls within a script.

Functions

analyze_function_calls(→ dict[str, list[str]])

Analyze function definitions and calls in a Python file.

Module Contents

class function_call_analyzer.FunctionCallAnalyzer

Bases: libcst.CSTVisitor

Tracks function definitions and calls within a script.

This visitor analyzes Python code to identify function definitions and track each time a function is called, allowing for the detection of unused functions and function call patterns.

function_defs

Set of defined function names

Type:

Set[str]

function_calls

Dictionary mapping function names to call counts

Type:

Dict[str, int]

get_call_counts() dict[str, int]

Get the call count for each defined function.

Returns:

Dictionary mapping function names to their call counts

Return type:

Dict[str, int]

report_unused_functions() list[str]

Find functions that are defined but never called.

Returns:

List of function names that are defined but never called

within the analyzed code

Return type:

List[str]

visit_Call(node: libcst.Call) None

Track function calls during the AST traversal.

This method increments the call count for functions when they are invoked. It only tracks direct function calls by name, not method calls or calls through variables.

Parameters:

node (Call) – The function call node being visited

visit_FunctionDef(node: libcst.FunctionDef) None

Track function definitions during the AST traversal.

This method adds each defined function name to the set of tracked functions.

Parameters:

node (cst.FunctionDef) – The function definition node being visited

function_calls: dict[str, int]
function_defs: set[str]
function_call_analyzer.analyze_function_calls(filepath: str) dict[str, list[str]]

Analyze function definitions and calls in a Python file.

This function parses a Python file, analyzes function definitions and calls, and reports various metrics including unused functions.

Parameters:

filepath (str) – Path to the Python file to analyze

Returns:

Dictionary with analysis results, including ‘unused_functions’

Return type:

Dict[str, List[str]]

Raises: