| 1 | [Bug]: get_backend() clears figures from Gcf.figs if they were created under rc_context |
| 2 | ### Bug summary |
| 3 | |
| 4 | calling `matplotlib.get_backend()` removes all figures from `Gcf` if the *first* figure in `Gcf.figs` was created in an `rc_context`. |
| 5 | |
| 6 | ### Code for reproduction |
| 7 | |
| 8 | ```python |
| 9 | import matplotlib.pyplot as plt |
| 10 | from matplotlib import get_backend, rc_context |
| 11 | |
| 12 | # fig1 = plt.figure() # <- UNCOMMENT THIS LINE AND IT WILL WORK |
| 13 | # plt.ion() # <- ALTERNATIVELY, UNCOMMENT THIS LINE AND IT WILL ALSO WORK |
| 14 | with rc_context(): |
| 15 | fig2 = plt.figure() |
| 16 | before = f'{id(plt._pylab_helpers.Gcf)} {plt._pylab_helpers.Gcf.figs!r}' |
| 17 | get_backend() |
| 18 | after = f'{id(plt._pylab_helpers.Gcf)} {plt._pylab_helpers.Gcf.figs!r}' |
| 19 | |
| 20 | assert before == after, '\n' + before + '\n' + after |
| 21 | ``` |
| 22 | |
| 23 | |
| 24 | ### Actual outcome |
| 25 | |
| 26 | ``` |
| 27 | --------------------------------------------------------------------------- |
| 28 | AssertionError Traceback (most recent call last) |
| 29 | <ipython-input-1-fa4d099aa289> in <cell line: 11>() |
| 30 | 9 after = f'{id(plt._pylab_helpers.Gcf)} {plt._pylab_helpers.Gcf.figs!r}' |
| 31 | 10 |
| 32 | ---> 11 assert before == after, '\n' + before + '\n' + after |
| 33 | 12 |
| 34 | |
| 35 | AssertionError: |
| 36 | 94453354309744 OrderedDict([(1, <matplotlib.backends.backend_qt.FigureManagerQT object at 0x7fb33e26c220>)]) |
| 37 | 94453354309744 OrderedDict() |
| 38 | ``` |
| 39 | |
| 40 | ### Expected outcome |
| 41 | |
| 42 | The figure should not be missing from `Gcf`. Consequences of this are, e.g, `plt.close(fig2)` doesn't work because `Gcf.destroy_fig()` can't find it. |
| 43 | |
| 44 | ### Additional information |
| 45 | |
| 46 | _No response_ |
| 47 | |
| 48 | ### Operating system |
| 49 | |
| 50 | Xubuntu |
| 51 | |
| 52 | ### Matplotlib Version |
| 53 | |
| 54 | 3.5.2 |
| 55 | |
| 56 | ### Matplotlib Backend |
| 57 | |
| 58 | QtAgg |
| 59 | |
| 60 | ### Python version |
| 61 | |
| 62 | Python 3.10.4 |
| 63 | |
| 64 | ### Jupyter version |
| 65 | |
| 66 | n/a |
| 67 | |
| 68 | ### Installation |
| 69 | |
| 70 | conda |