◐ Shell
clean mode source ↗

Do not enable default Matplotlib backend when checking what the backend is by ianthomas23 · Pull Request #38 · ipython/matplotlib-inline

Fixes #37 and #25.

When importing backend_inline the function _enable_matplotlib_integration() is automatically called and this checks what the current Matplotlib backend is. Previously calling matplotlib.get_backend() if no backend was currently set would as a side-effect force it to be the default backend for that OS rather than leaving it unset. Changing it to matplotlib.rcParams._get("backend") avoids the side-effect thus fixing the problem.

Although rcParams._get is a private function this is in fact the correct function to use as explained in the Matplotlib source code:
https://github.com/matplotlib/matplotlib/blob/eb812a8e479d0bcf43a30232c31afec78963ed53/lib/matplotlib/__init__.py#L698-L713

To reproduce the original problem and confirm this PR fixes it use the following on the main branch and this PR branch:

  1. Create file ~/.ipython/profile_default/ipython_kernel_config.py containing the single line c.InteractiveShellApp.matplotlib = 'inline'.
  2. Use either jupyter lab or jupyter qtconsole and run the following code: import matplotlib.pyplot as plt; plt.plot([1,3,2])

On main branch this uses the wrong Matplotlib backend and on this PR branch it used the correct inline backend.

I have manually tested other use cases of using Matplotlib in ipython and jupyter and it looks like this fix does not introduce any new problems.