Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support for reusing widgets in interact without leaking subscriptions #3882

Open
FeldrinH opened this issue Jan 31, 2024 · 0 comments
Open

Comments

@FeldrinH
Copy link

FeldrinH commented Jan 31, 2024

Problem

Consider a simple notebook consisting of these two cells:

from ipywidgets import IntSlider

slider = IntSlider(1, min=0, max=10)
%matplotlib widget

import matplotlib.pyplot as plt
import numpy as np
from ipywidgets import interact

fig = plt.figure('test')

count = 0

def plot(val):
    global count

    fig.clear()
    ax = fig.gca()
    x = np.arange(1, 10, 0.02)
    y = np.cos(x * val)
    ax.plot(x, y)

    count += 1
    print(count)

interact(plot, val=slider)

plt.show()

I would like to declare the input widgets in a separate cell, as shown in this example, because that allows me to
a) change the plotting code without resetting the input values,
b) reuse the same input values in multiple cells with multiple interact calls and possibly other code.

However, this approach has a big drawback: every time I run the cell with interact in it, it subscribes to the slider input event again, and old subscriptions from previous runs are not removed. This means that changing the input slider value once will rerun the plotting code once for each time I reran the cell with interact (this can be verified by observing the change in count when moving the slider one step). After n reruns, every change to the input value causes the plotting code to rerun n times.

After about 10 reruns this makes each interactive update noticeably slower and after about 40 reruns the performance becomes sluggish to the point of being practically unusable.

Note: I have a reasonably powerful desktop computer (Intel i5-13600KF CPU) and this is a fairly simple plot. On slower computers or with more complex plots you will reach these thresholds earlier.

Proposed Solution

Ideally interact widgets would automatically remove these subscriptions once they are no longer visible. I don't know how complex this would be to implement.

If that is not feasible for technical reasons then it would be nice to at least have a public API function to clear all subscriptions on an input widget (perhaps there already is something for this, but I could not find it using the existing documentation).

Additional context

Tested with ipywidgets==8.1.1, jupyterlab==4.0.11 and jupyter_server==2.12.5.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant