From e60c06a57de9f1e53fdd4b3a16c6a16c530e4f2a 2024-02-16 10:20:15
From: M Bussonnier <bussonniermatthias@gmail.com>
Date: 2024-02-16 10:20:15
Subject: [PATCH] Delay import from matplotlib_inline.backend_inline (#14330)

Possible fix for #14329.

With this change, the reproducers from the issue become:
```python
$ ipython
<snip>

In [1]: import matplotlib.pyplot as plt; plt.set_loglevel("debug")

In [2]: %matplotlib tk
DEBUG:matplotlib.pyplot:Loaded backend TkAgg version 8.6.
```

It is still possible to call `matplotlib.pyplot.switch_backend` twice
but only if you request `%matplotlib inline`, and the `switch_backend`
is called with same correct backend twice. This isn't ideal but it
doesn't cause any problems apart from being a little slower than
necessary.
---

diff --git a/IPython/core/interactiveshell.py b/IPython/core/interactiveshell.py
index 904f7b2..12c1206 100644
--- a/IPython/core/interactiveshell.py
+++ b/IPython/core/interactiveshell.py
@@ -3654,8 +3654,6 @@ class InteractiveShell(SingletonConfigurable):
             make sense in all contexts, for example a terminal ipython can't
             display figures inline.
         """
-        from matplotlib_inline.backend_inline import configure_inline_support
-
         from IPython.core import pylabtools as pt
         gui, backend = pt.find_gui_and_backend(gui, self.pylab_gui_select)
 
@@ -3670,6 +3668,9 @@ class InteractiveShell(SingletonConfigurable):
                 gui, backend = pt.find_gui_and_backend(self.pylab_gui_select)
 
         pt.activate_matplotlib(backend)
+
+        from matplotlib_inline.backend_inline import configure_inline_support
+
         configure_inline_support(self, backend)
 
         # Now we must activate the gui pylab wants to use, and fix %run to take