Skip to content

ipympl changes MPL backend on import #623

Description

@sappelhoff

In mne-python (see above), we have a functionality called sys_info, which gives us (among other things) the versions of all sorts of installed packages.

For this reason, we also import ipympl.

At import time, ipympl actually changes the MPL backend.

Is this something that could be avoided? This change in backend was very surprising to us and it took an in-depth profiling to identify it as the cause of a massive memory leak in a pipeline that produced several plots on each iteration, never closing them due to the backend change.

Activity

  1. ianhi commented on Jun 15, 2026

    @ianhi
    Collaborator

    Hmm I agree that that is a bad behavior. I suspect this can be changed depending on how the %matplotlib ipympl magic and matplotlib backend import works.

    Some relevant code paths from a quick check

    https://github.com/matplotlib/matplotlib/blob/fe78309725e02eb679c29ce24029c5576ab4bb14/lib/matplotlib/backends/registry.py#L139-L151

    https://github.com/ipython/ipython/blob/fdbdf1c699e80f76a71e3dc5b46a3d164939b3f2/IPython/core/pylabtools.py#L38-L40

    The actual lines that cause the backend to be changed on import.

    # __init__.py is used by the nbextension installation.
    # Conda cannot have dependencies for post-link scripts.
    if 'matplotlib' in sys.modules:
    import matplotlib
    matplotlib.use('module://ipympl.backend_nbagg')

    which are 8 years old and nbextension is no longer relevant so I'm pretty sure we can just remove that entirely. But would love to hear what @martinRenou thinks before doing that

    As a workaround for now you can try directly importing from _version

    In [1]: from ipympl._version import version_info
    
    In [2]: version_info
    Out[2]: (0, 10, 0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions