Skip to main content

A lightweight Python library for tracing function call relationships and visualizing them as interactive graphs

Project description

CallFlow Tracer ๐Ÿง 

A lightweight Python library for tracing function call relationships and visualizing them as interactive graphs. Perfect for understanding code flow, debugging performance issues, and documenting how your code works.

PyPI version Python Version License: MIT Downloads Code style: black

What's New in 0.2.2 (2025-09-28)

  • Stability Fixes in Tracer Core: Hardened error handling in CallTracer._trace_calls, preventing silent failures and ensuring test programs run to completion.
  • Decorator/Scope Interop: Resolved conflicts between the @trace decorator and trace_scope context manager; improved caller detection and global state management.
  • Improved JSON Export: Fixed "network.getData is not a function" by exporting from original nodes/edges, added richer metadata and better error handling.
  • UI Enhancements (HTML Exporter):
    • Added a modern, collapsible CPU profiling section with gradient header and dark code theme.
    • Implemented working module filter with smooth zoom-to-fit and edge filtering.
    • Restored Circular and Timeline layouts with correct positioning and auto-fit behavior.
  • Version Sync: Package version aligned across pyproject.toml and callflow_tracer/__init__.py.

Thank you to users for feedback that helped guide these improvements.

โœจ Features

  • Simple API: Just add @trace decorator or use with trace_scope():
  • Interactive Visualizations: Beautiful HTML graphs with zoom, pan, and filtering
  • Performance Profiling: Track execution time, memory usage, and bottlenecks
  • Detailed Call Analysis: View call hierarchies and timing breakdowns
  • Privacy-Focused: Optionally anonymize function arguments
  • Multiple Formats: Export to JSON or interactive HTML
  • Zero Dependencies: Works out of the box (except for networkx for graph operations)

๐Ÿš€ Quick Start

Installation

From PyPI (Recommended)

pip install callflow-tracer

From Source

git clone https://github.com/rajveer43/callflow-tracer.git
cd callflow-tracer
pip install -e .

Development Installation

git clone https://github.com/rajveer43/callflow-tracer.git
cd callflow-tracer
pip install -e ".[dev]"

๐Ÿ” Advanced Profiling Examples

Memory and Performance Profiling

from callflow_tracer import profile_function, profile_section, get_memory_usage
import time
import random
import numpy as np

@profile_function
def process_data(data_size: int) -> float:
    """Process data with CPU and memory profiling."""
    # Allocate memory
    data = [random.random() for _ in range(data_size)]
    
    # CPU-intensive work
    total = sum(data) / len(data) if data else 0
    
    # Simulate I/O
    time.sleep(0.1)
    
    return total

def analyze_performance():
    """Example using profile_section context manager."""
    with profile_section("Data Processing"):
        # Process different data sizes
        for size in [1000, 10000, 100000]:
            with profile_section(f"Processing {size} elements"):
                result = process_data(size)
                print(f"Result: {result:.4f}")
                
                # Get memory usage
                mem_usage = get_memory_usage()
                print(f"Memory usage: {mem_usage:.2f} MB")

if __name__ == "__main__":
    analyze_performance()
    
    # Export the profile data to HTML
    from callflow_tracer import export_html
    export_html("performance_profile.html")

Visualizing Performance Data

After running the above code, you can view the performance data in an interactive HTML report that includes:

  • Call hierarchy with timing information
  • Memory usage over time
  • Hotspots and bottlenecks
  • Function execution statistics

๐Ÿ›  Basic Usage

Option 1: Decorator Approach

from callflow_tracer import trace, trace_scope

@trace
def calculate_fibonacci(n):
    if n <= 1:
        return n
    return calculate_fibonacci(n-1) + calculate_fibonacci(n-2)

@trace
def main():
    result = calculate_fibonacci(10)
    print(f"Fibonacci(10) = {result}")

# Trace everything and export to HTML
with trace_scope("fibonacci_trace.html"):
    main()

Option 2: Context Manager Approach

from callflow_tracer import trace_scope

def process_data():
    data = load_data()
    cleaned = clean_data(data)
    result = analyze_data(cleaned)
    return result

def load_data():
    return [1, 2, 3, 4, 5]

def clean_data(data):
    return [x * 2 for x in data if x > 2]

def analyze_data(data):
    return sum(data) / len(data)

# Trace the entire process
with trace_scope("data_processing.html"):
    result = process_data()
    print(f"Analysis result: {result}")

๐Ÿ“Š What You Get

After running your traced code, you'll get an interactive HTML file showing:

  • Function Nodes: Each function as a colored node (color indicates performance)
  • Call Relationships: Arrows showing which functions call which others
  • Performance Metrics: Hover over nodes to see call counts and timing
  • Interactive Controls: Filter by module, toggle physics, change layout
  • Statistics: Total functions, call relationships, and execution time

๐ŸŽฏ Advanced Usage

Custom Export Options

from callflow_tracer import trace_scope, export_json, export_html

with trace_scope() as graph:
    # Your code here
    my_application()
    
# Export to different formats
export_json(graph, "trace.json")
export_html(graph, "trace.html", title="My App Call Flow")

Selective Tracing

from callflow_tracer import trace

# Only trace specific functions
@trace
def critical_function():
    # This will be traced
    pass

def regular_function():
    # This won't be traced
    pass

# Use context manager for broader tracing
with trace_scope("selective_trace.html"):
    critical_function()  # Traced
    regular_function()   # Not traced

Performance Analysis

from callflow_tracer import trace_scope, get_current_graph

with trace_scope("performance_analysis.html"):
    # Your performance-critical code
    optimize_algorithm()
    
# Get the graph for programmatic analysis
graph = get_current_graph()
for node in graph.nodes.values():
    if node.avg_time > 0.1:  # Functions taking > 100ms
        print(f"Slow function: {node.full_name} ({node.avg_time:.3f}s avg)")

๐Ÿ”ง Configuration

HTML Export Options

from callflow_tracer import export_html

# Customize the HTML output
export_html(
    graph, 
    "custom_trace.html",
    title="My Custom Title",
    include_vis_js=True  # Include vis.js from CDN (requires internet)
)

Privacy Settings

The library automatically truncates function arguments to 100 characters for privacy. For production use, you can modify the CallNode.add_call() method to further anonymize or exclude sensitive data.

๐Ÿ“ Project Structure

callflow-tracer/
โ”œโ”€โ”€ callflow_tracer/
โ”‚   โ”œโ”€โ”€ __init__.py          # Main API
โ”‚   โ”œโ”€โ”€ tracer.py            # Core tracing logic
โ”‚   โ””โ”€โ”€ exporter.py          # JSON/HTML export
โ”œโ”€โ”€ pyproject.toml           # Package configuration
โ”œโ”€โ”€ README.md               # This file
โ””โ”€โ”€ LICENSE                 # MIT License

๐ŸŽจ Visualization Features

The generated HTML includes:

  • Interactive Network: Zoom, pan, and explore your call graph
  • Color Coding:
    • ๐Ÿ”ด Red: Slow functions (>100ms average)
    • ๐ŸŸข Teal: Medium functions (10-100ms average)
    • ๐Ÿ”ต Blue: Fast functions (<10ms average)
  • Filtering: Filter by module to focus on specific parts of your code
  • Layout Options: Hierarchical or force-directed layouts
  • Physics Controls: Enable/disable physics simulation
  • Hover Details: Rich tooltips with performance metrics

๐Ÿšจ Important Notes

  • Performance Impact: Tracing adds overhead. Use selectively for production code
  • Thread Safety: The tracer is thread-safe and can handle concurrent code
  • Memory Usage: Large applications may generate substantial trace data
  • Privacy: Function arguments are truncated by default for security

๐Ÿค Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

๐Ÿ™ Acknowledgments

  • Built with NetworkX for graph operations
  • Visualizations powered by vis.js
  • Inspired by the need for better code understanding and debugging tools

๐Ÿ“ž Support


Happy Tracing! ๐ŸŽ‰

CallFlow Tracer makes understanding your code as easy as pip install callflow-tracer

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

callflow_tracer-0.2.2.tar.gz (38.9 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

callflow_tracer-0.2.2-py3-none-any.whl (31.7 kB view details)

Uploaded Python 3

File details

Details for the file callflow_tracer-0.2.2.tar.gz.

File metadata

  • Download URL: callflow_tracer-0.2.2.tar.gz
  • Upload date:
  • Size: 38.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.10

File hashes

Hashes for callflow_tracer-0.2.2.tar.gz
Algorithm Hash digest
SHA256 e113913456493e95d4698ba71e526abecdd630403a3a6e40d2eeb5c23b06035f
MD5 cc01479a4ab2630703666d74fc653a5e
BLAKE2b-256 bc98646d20bc05e2e2c90a493dec0f2eb3248b4ed612ca2920a1433b6bc0479b

See more details on using hashes here.

File details

Details for the file callflow_tracer-0.2.2-py3-none-any.whl.

File metadata

File hashes

Hashes for callflow_tracer-0.2.2-py3-none-any.whl
Algorithm Hash digest
SHA256 9c38f572ce5bcc79c8aba291ef54cd79e75d012d5049b94c2cf4b4adeec320f8
MD5 9bda9803be2833d6f7be679374db7391
BLAKE2b-256 de2f11459ffef84eb3af38184e7ffd34c279c49a886612aad709a3d0596cf201

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page