Skip to content

[ENH]: Provide a standard place to manually register widgets/animations on a figure/artist/etc. #26881

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

Open
anntzer opened this issue Sep 22, 2023 · 0 comments

Comments

@anntzer
Copy link
Contributor

anntzer commented Sep 22, 2023

Problem

It is well known that references must be kept to widgets to keep them responsive and to animations to keep them running. Yet sometimes there's no obvious place to stash them, e.g. (minimal example, fill in real-world usage as desired)

import matplotlib.pyplot as plt
from matplotlib.widgets import Cursor

def main():
    fig, ax = plt.subplots(figsize=(8, 6))
    cursor = Cursor(ax)
    plt.show()

main()

If you run this in non-interactive mode (e.g. saved in module.py and run from an external shell) then you are fine because show() blocks and thus the function frame keeps a reference to the cursor. But if you run this in interactive mode (e.g. from an IPython shell -- import module; module.main()) then show() is non-blocking and immediately returns, so while the figure is displayed, the cursor is gc'ed.

As the developer of module.py, if you want to guard against this problem, then you need either to promote your simple function to a full-blown custom class holding the figure and the cursor, or you can go for the "practical" approach of stashing a reference to the cursor at the only reasonable place to do so: fig._cursor_ref = cursor (or similarly as an axes attribute). But adding a custom attribute on the figure for that purpose feels rather dirty, and I guess that static type checkers probably don't like that at all either (not that I've checked...).

Proposed solution

Provide e.g. Figure.register_child/register_widget/register_animation (name up to bikeshedding, and I'm not sure either whether that should just exist on Figures or on all Artists), which simply appends the child object (a widget or an animation, typically) to an internal list whose purpose is only to keep it alive. Perhaps also provide a manual unregistration method.

(Many, including myself, have argued elsewhere that widgets and animations should be auto-kept alive anyways, but I can understand the arguments against that behavior; in this issue I'm just arguing that we should have a standard way to manually register widgets and animations as to be kept alive.)

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

No branches or pull requests

1 participant