Skip to main content

RecursionLens

English | 简体中文

See not just what recursion returns, but where the repeated work happens.

Try RecursionLens in the browser. The playground runs CS1302A examples with Pyodide and needs no installation. Follow a call from the tree to the subproblem graph, inspect a Recursion Doctor finding, or predict how much memoization will save. Browser walkthrough

RecursionLens is a zero-runtime-dependency Python package for exploring recursive execution in JupyterLab. It turns a traced run into an expandable call tree, a compressed subproblem DAG, and a quantitative naive-versus-memoized comparison.

JupyterLab tutorial, already executed: Open RecursionLens_Tutorial.ipynb (简体中文版). Sixteen code cells have saved output; the final cell opens the interactive player when you run it in a live kernel. If Jupyter hides HTML/SVG from a downloaded notebook, use its Trust action or click Run All Cells once. For a zero-setup preview, download and open the static HTML companion or its Chinese version.

Screenshots

JupyterLab — execution comparison. report.compare() renders a metrics table and both DAGs inside the notebook, including how many bodies ran and how many calls were served from a cache.

RecursionLens comparison report rendered in JupyterLab

Web playground — step-through player. The call tree grows as the code runs: returned calls stay on screen in green, the current call is coral, and the current frame's locals sit underneath the tree.

RecursionLens step-through player in the browser

Project team

CS1302A Group 50:

  • Ziyu JIANG
  • Xinyue CAI
  • Kehan CAO
  • Ruoxi LYU
  • Haobo MA

Why RecursionLens?

RecursionLens grew out of a beginner's own difficulty with recursion. Loops can be read line by line, but a non-tail-recursive call such as fib or a tree traversal expands into many interleaved calls: the same subproblem is entered again and again, and a value only comes back after its whole subtree has finished. The step-by-step mentor provided by our course (OPT) is excellent for ordinary programs, since it shows one execution step at a time, yet a recursive run becomes a long stream of push and pop steps with no view of the overall shape of the computation, and no indication of which subproblems repeat. The usual fallback is to draw the call tree by hand on paper. RecursionLens automates that drawing and adds the numbers a hand-drawn tree cannot show.

It answers three different questions:

  1. Call tree: what actually happened, invocation by invocation?
  2. Subproblem DAG: how many distinct problems and dependencies exist after identical arguments are merged?
  3. Execution comparison: what changes when memoization is enabled?

For fib(5), that story is 15 observed calls → 6 unique subproblems → 6 executed bodies with memoization.

Innovation beyond a call graph

The existing rcviz package documents decorator-based recursion trees with arguments, return values, and Jupyter rendering. RecursionLens deliberately focuses on a different workflow:

  • transform one trace between an invocation tree and a compressed subproblem DAG;
  • show the complete call tree at once in an SVG view or keep a collapsible tree for larger runs;
  • quantify repeated calls, executed bodies, cache hits, and maximum depth;
  • compare naive and memoized runs in one report with side-by-side DAGs;
  • render self-contained HTML/SVG in JupyterLab without Graphviz, native libraries, external JavaScript, or a CDN;
  • export versioned JSON for reproducible analysis and testing.

Installation

RecursionLens requires Python 3.9 or later.

Install from PyPI:

python -m pip install recursionlens

For local development:

git clone https://github.com/ZiyuJiang07/recursionlens.git
cd recursionlens
python -m pip install -e ".[dev]"

The package has no runtime dependencies. The interactive tutor is the only optional extra, and it needs ipywidgets.

Quickstart in JupyterLab

from recursionlens import trace

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

naive = fib.run(5)
naive  # expandable call tree in the notebook output area

Switch the same trace to the compressed subproblem DAG:

naive.show(mode="dag")

Or show every call at once as one compact SVG tree, with no nodes collapsed:

naive.show(mode="expanded")

Run the function again with memoization and compare the evidence:

memoized = fib.with_options(memoize=True).run(5)
comparison = naive.compare(memoized)
comparison

The comparison confirms the returned values match and reports the measured changes, including 15 → 6 executed function bodies.

Normal function behavior is preserved:

assert fib(5) == 5
assert fib.last_report.total_calls == 15

Step through a function line by line

Version 0.2.0 adds a Python Tutor-style player that runs inside the notebook. Paste a function, choose the call, and step through it:

from recursionlens import tutor

tutor()   # editable code panel, an input box for the call, and step controls

The player highlights the current line and grows the call tree as the run proceeds: waiting calls are blue, the call being executed is coral, and returned calls stay on screen in green. The current frame's local variables sit under the tree, and changing the call (for example fib(5) → fib(3)) records a fresh run and redraws from a single node. It reports each call, line, return, and exception, which makes the order of a recursion easy to follow.

The tutor runs the code you paste with normal Python semantics; it is not a sandbox.

tutor() needs ipywidgets:

python -m pip install "recursionlens[tutor]"

The recording is plain Python, so it also works without the widget:

from recursionlens import record_tutor

trace = record_tutor("def fib(n): ...", "fib(5)")
print(trace.describe())
trace.steps[0].frames        # stack snapshot for one step

Inspect a call in the browser

Open the online playground and wait for the default fib(5) trace to load.

In Step through, use Play to watch the call tree grow one step at a time. Click Pause to inspect the current frame, or drag the slider to jump to a step.

  1. Open Expanded tree and click a fib(2) node. The Trace inspector shows its call path. One path is fib(5) → fib(4) → fib(3) → fib(2). In Call tree, use the Inspect button next to a call.
  2. Click Show in DAG. The three calls to fib(2) share one subproblem node. Select an entry under Recorded calls to jump back to that invocation in the tree.
  3. Open Recursion Doctor. Find the entry for repeated fib(2) work and click a Show call button to see the evidence in the tree.

The Doctor reports what it observed in the recorded calls for the selected input. If a call re-enters a subproblem that is still on the stack, check the stopping condition and recursive arguments. For functions whose results depend only on their arguments and that have no side effects, repeated work across branches is a reason to investigate memoization.

Try Debug a base case under Examples and exercises. In Recursion Doctor, click Show call to follow the error to reciprocal_sum(n=0). Change the base case to return 0 and rerun to check the fix. Open the debugging exercise

To share a built-in exercise, choose it under Examples and exercises and click Copy example link. The link opens the exercise with its original code and input. After editing the code or input, select a built-in exercise again to copy its link. Open the Grid paths exercise

To preview a local checkout, run python -m http.server 8000 from the repository root and open the local playground.

Predict cache savings

  1. Use the default fib(5) or choose Grid paths under Examples and exercises to load paths(3, 3).
  2. Click Predict cache savings and enter how many function body executions you expect memoization to skip.
  3. Press Run and check to see your guess next to the measured savings in Compare. The feedback shows the number of executions in both runs and how often the memoized run reused a result.

The exercise checks predictions when both runs finish successfully with matching return values. Use a function without its own cache, whose result depends only on its arguments and which has no side effects. For Grid paths, different orders of moving right and down can leave the same number of steps in each direction.

Check the grid path result

paths(3, 3) returns 20 routes. Memoization reduces function body executions from 39 to 15, saving 24 executions with 4 cache hits.

Compare growth across input sizes

Growth measures the Python code currently in the editor. Click Growth beside Run to open its controls. Set a call template and input range for your function. When the main input call matches a function in your code, Growth suggests a template by replacing its first integer argument with {n}.

For example, paste this function, then click Growth:

def countdown(n):
    return 0 if n == 0 else 1 + countdown(n - 1)

In Growth, use countdown({n}), From 1, To 8, and Step 1. Click Measure current code. The table will show 2 through 9 function executions, and the fitted shape is linear. Both runs start from fresh state at every input size.

For multiple inputs, paths({n}, {n}) varies both dimensions. For a function that accepts a list, a template such as sum_list(list(range({n}))) varies the list length. The Exact counts table and Download CSV use the results from your code.

The two estimate lines fit executions with and without memoization separately against O(1), O(log n), O(n), O(n log n), O(n²), and O(2ⁿ). They describe the measured function body executions over the chosen range. Work inside loops can grow while function body counts stay constant. Each measurement accepts up to 30 input sizes and stops after 200,000 traced code steps or five seconds.

The same fitting calculation is available in Python:

from recursionlens import fit_growth

fit = fit_growth([1, 2, 3, 4, 5], [2, 4, 6, 8, 10])
print(fit.model, fit.r2)  # O(n) 1.0

Export a report

In Growth, click Download CSV to save the input sizes and measured counts for a spreadsheet. In JSON, click Download JSON to save the current trace report when it is available.

naive.export_html("fib-tree.html")
naive.export_html("fib-dag.html", mode="dag")
naive.export_json("fib-trace.json")
comparison.export_html("fib-comparison.html")

HTML reports are standalone files that can be opened without a notebook server. JSON contains the tree, DAG nodes and edges, metrics, warnings, and schema version.

Supported scope

Version 0.2.0 targets synchronous, deterministic teaching examples such as factorial, Fibonacci, and pure mathematical recursion.

  • Memoization requires hashable bound arguments; unhashable arguments produce a warning instead of a crash.
  • Identical arguments do not necessarily imply redundant work for functions with side effects or external state.
  • max_calls caps the stored call tree. Observed calls, executed bodies, and cache hits cover the full run. After truncation, tree and DAG metrics describe the recorded calls.
  • RecursionLens executes your function; it is not a sandbox for untrusted code.
  • Async functions, generators, automatic Big-O inference from source code, and automatic code rewriting are non-goals for 0.2.0. fit_growth() fits counts you measure; it does not infer complexity from source.

Documentation and demo

Development and testing

python -m pytest tests -v
python -m build
python -m twine check dist/*

The test suite covers trace invariants, cache behavior, signatures, exceptions, truncation, JSON, HTML escaping, DAG rendering, and comparison reports. Contributions should keep the public API, tests, and README synchronized.

Documentation is bilingual: README.md / README.zh-CN.md and docs/RecursionLens_Tutorial.ipynb / docs/RecursionLens_Tutorial.zh-CN.ipynb must be updated together, including their generated HTML files.

License

MIT © 2026 Ziyu JIANG, Xinyue CAI, Kehan CAO, Ruoxi LYU, Haobo MA.

Metadata

Release files for recursionlens 0.2.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for recursionlens 0.2.2
File Size Uploaded Provenance Actions
recursionlens-0.2.2.tar.gz 56.2 kB Without provenance Details for recursionlens-0.2.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for recursionlens 0.2.2
File Interpreter ABI Platform Actions
recursionlens-0.2.2-py3-none-any.whl Python 3 none any Details for recursionlens-0.2.2-py3-none-any.whl

Total release size: 95.1 kB

Release files / recursionlens-0.2.2.tar.gz

Download URL recursionlens-0.2.2.tar.gz
Size 56.2 kB
Tags Source
SHA-256 checksum
How to use checksums
1b6073e93ed3975652bfc57f611ab72442b67afc9737b9cba87ddc8c65877369
BLAKE2b-256 checksum
How to use checksums
578dfd26f27f72e1daa4d7313ff121f82956a42b7934e910da10f3517ffb27ec
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Release files / recursionlens-0.2.2-py3-none-any.whl

Download URL recursionlens-0.2.2-py3-none-any.whl
Size 38.9 kB
Tags Python 3
SHA-256 checksum
How to use checksums
ab0e96fd5822fe33c214931acaa5d9761c692f9645151eed5256cd79b93684c7
BLAKE2b-256 checksum
How to use checksums
eab6b9773124e2656b513bad97dc2796260bf151d3ed3b44490ecee0f2cbe8f0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.12

Security for recursionlens 0.2.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page