Overview
TheVisualiser class is the core decorator that intercepts recursive function calls and builds a visual tree representation. When applied to a recursive function, it automatically tracks each function call, captures arguments and return values, and generates a graph structure that can be exported as images or animations.
Class signature
Parameters
List of argument names to exclude from the node labels in the visualization. By default, the internal
node_num argument is always ignored. Any additional argument names provided will be appended to this list.Default behavior: ['node_num']Controls whether argument names are displayed alongside their values in node labels.
- When
True: displays askey=value(e.g.,n=5) - When
False: displays only values (e.g.,5)
Controls whether the return value of each function call is displayed in the node.
- When
True: appends=> {result}to the node label - When
False: shows only the function call signature
"record" via node_properties_kwargs, the return value is separated by a row delimiter instead of a newline.Dictionary of graphviz node properties to customize the visual appearance of nodes in the recursion tree. Accepts any valid graphviz node attributes.Common properties include:
shape: Node shape (e.g.,"record","box","ellipse")color: Border colorstyle: Node style (e.g.,"filled","solid","dashed")fillcolor: Fill color when style is"filled"
Usage as a decorator
TheVisualiser class is designed to be used as a Python decorator. Apply it to any recursive function to automatically visualize its execution tree.
Basic usage
With custom configuration
Ignoring specific arguments
How it works
The__call__ method (visualiser/visualiser.py:153-271) implements the decorator logic:
- Call interception: Wraps the decorated function using
functools.wraps - Node tracking: Assigns a unique
node_numto each function call - Argument extraction: Captures function arguments and formats them according to configuration
- Parent tracking: Uses Python’s stack frames to identify caller functions and build edges
- Graph construction: Creates nodes and edges using the pydot library
- Return value capture: Intercepts the function’s return value and optionally displays it
The decorator adds a hidden
node_num keyword argument to uniquely identify each node in the recursion tree. This argument is automatically removed before the actual function call.Class attributes
The following class-level attributes are initialized byinit_graph() and shared across all instances:
node_count: Counter for total number of function callsgraph: pydot.Dot graph object withbgcolor="#fff3af"stack: List tracking the call stack for building parent-child relationshipsedges: List of edge strings in DOT formatnodes: List of node strings in DOT format