Skip to main content

An interactive step-by-step Python code execution visualizer

Project description

Python Logo

๐Ÿ Python Code Visualizer

An interactive step-by-step Python code execution visualizer

Features โ€ข Installation โ€ข Quick Start โ€ข API โ€ข Examples โ€ข Contributing

Python 3.8+ MIT License Production Ready PRs Welcome


โœจ Overview

Python Code Visualizer is a powerful library that helps developers and educators understand Python code execution by generating interactive, step-by-step visualizations. Watch your code come alive as you trace through variables, function calls, and control flow.

Demo Preview


๐ŸŽฏ Features

๐Ÿ” Execution Tracing

  • Line-by-line code execution
  • Variable state tracking
  • Function call/return visualization
  • Exception handling display

๐Ÿ“Š Visual Analytics

  • Execution heatmap (hot loops)
  • Timeline event markers
  • Call stack visualization
  • Scope separation (locals/globals)

๐Ÿ›ก๏ธ Safety & Robustness

  • Timeout protection (default: 10s)
  • Step limit (default: 10,000)
  • HTML escaping (XSS prevention)
  • Empty code validation

๐ŸŽจ Rich UI

  • VS Code-inspired dark theme
  • Syntax highlighting (highlight.js)
  • Keyboard navigation
  • Playback controls

๐Ÿ“ฆ Installation

Prerequisites

  • Python 3.8 or higher
  • pip package manager

Install via pip

# Clone the repository
git clone https://github.com/jayachandranpm/python-code-visualizer.git
cd python-code-visualizer

# Install dependencies
pip install -r requirements.txt

Dependencies

Package Version Purpose
jinja2 โ‰ฅ3.0.0 HTML template rendering

๐Ÿš€ Quick Start

Basic Usage

from PythonVisualizer import CodeVisualizer

code = """
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
total = sum(squares)
print(f"Sum of squares: {total}")
"""

# Create visualizer
viz = CodeVisualizer(code)

# Execute and capture trace
viz.execute()

# Generate HTML visualization
viz.render(output_file='visualization.html')

Then open visualization.html in your browser! ๐ŸŽ‰


๐Ÿ“– API Reference

CodeVisualizer

The main entry point for the library.

CodeVisualizer(
    code: str,                    # Python code to visualize
    inputs: list = None,          # Mock inputs for input() calls
    timeout: float = 10.0,        # Execution timeout in seconds
    max_steps: int = 10000        # Maximum trace steps
)

Methods

Method Description Returns
execute() Runs the code and captures trace dict with steps, counts, limit_reached
render(format='web', output_file='visualization.html') Generates visualization File path or HTML string

๐Ÿ’ก Examples

Example 1: Recursive Function

from PythonVisualizer import CodeVisualizer

code = """
def factorial(n):
    if n <= 1:
        return 1
    return n * factorial(n - 1)

result = factorial(5)
print(f"5! = {result}")
"""

viz = CodeVisualizer(code)
viz.execute()
viz.render(output_file='factorial.html')

What you'll see:

  • ๐ŸŸข Green markers for each recursive call
  • ๐ŸŸ  Orange markers for each return
  • ๐Ÿ“š Deep call stack during recursion

Example 2: User Input Handling

from PythonVisualizer import CodeVisualizer

code = """
name = input("What's your name? ")
age = input("How old are you? ")
print(f"Hello {name}, you are {age} years old!")
"""

# Provide mock inputs
viz = CodeVisualizer(code, inputs=["Alice", "25"])
viz.execute()
viz.render(output_file='input_demo.html')

What you'll see:

  • ๐Ÿ’ฌ Terminal shows the conversation
  • ๐Ÿ“ Variables update with input values

Example 3: Exception Visualization

from PythonVisualizer import CodeVisualizer

code = """
def divide(a, b):
    return a / b

result = divide(10, 0)  # This will crash!
"""

viz = CodeVisualizer(code)
viz.execute()
viz.render(output_file='exception.html')

What you'll see:

  • ๐Ÿ”ด Red highlighted crash line
  • โš ๏ธ Error banner with exception details
  • ๐Ÿ”ด Red marker on timeline

๐ŸŽฎ Keyboard Shortcuts

Key Action
โ† Step backward
โ†’ Step forward
Space Play / Pause

๐Ÿ—๏ธ Project Structure

PythonVisualizer/
โ”œโ”€โ”€ __init__.py              # Package exports
โ”œโ”€โ”€ api.py                   # CodeVisualizer class
โ”œโ”€โ”€ core/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ parser.py            # AST validation
โ”‚   โ”œโ”€โ”€ tracer.py            # sys.settrace logic
โ”‚   โ””โ”€โ”€ executor.py          # Code execution engine
โ”œโ”€โ”€ visualization/
โ”‚   โ”œโ”€โ”€ __init__.py
โ”‚   โ”œโ”€โ”€ web_renderer.py      # HTML generation
โ”‚   โ””โ”€โ”€ templates/
โ”‚       โ””โ”€โ”€ view.html.j2     # Jinja2 template
โ””โ”€โ”€ utils/
    โ”œโ”€โ”€ __init__.py
    โ””โ”€โ”€ serializer.py        # Object serialization

๐Ÿ”’ Security

Python Code Visualizer includes multiple security measures:

Feature Description
Timeout Prevents infinite loops (configurable)
Step Limit Prevents memory exhaustion
HTML Escaping Prevents XSS attacks in output
Sandboxed Execution Code runs with limited globals

โš ๏ธ Warning: This library executes arbitrary Python code. Only visualize code you trust.


๐Ÿค Contributing

Contributions are welcome! Please read our Contributing Guide first.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

๐Ÿ“„ License

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


๐Ÿ™ Acknowledgments


Made with โค๏ธ by developers, for developers

GitHub Stars

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

python_code_visualizer-1.0.2.tar.gz (4.1 MB view details)

Uploaded Source

Built Distribution

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

python_code_visualizer-1.0.2-py3-none-any.whl (17.7 kB view details)

Uploaded Python 3

File details

Details for the file python_code_visualizer-1.0.2.tar.gz.

File metadata

  • Download URL: python_code_visualizer-1.0.2.tar.gz
  • Upload date:
  • Size: 4.1 MB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.2

File hashes

Hashes for python_code_visualizer-1.0.2.tar.gz
Algorithm Hash digest
SHA256 f7a5a9661dd72e0a26f0ad44789edef0bde4953886f63ade83c8e265acfba796
MD5 cd0f68cdb0203d04868d2bb8e03ef880
BLAKE2b-256 8f9bf24964b1467644a2a4987830962f1327734922dafbdc58413129ea568d21

See more details on using hashes here.

File details

Details for the file python_code_visualizer-1.0.2-py3-none-any.whl.

File metadata

File hashes

Hashes for python_code_visualizer-1.0.2-py3-none-any.whl
Algorithm Hash digest
SHA256 b18d90c674955720c4a29a7957c2bfafa19c3085d76bd12a3df7a6c99133940a
MD5 fd4d6a78b7356c3f104b1e9812e02fca
BLAKE2b-256 6337649dd6d77814411ebaeb0f5155ccfa16e4cb53a06d95ff80a604b90c4703

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