2

When working with my python package, a certain function has some interactive matplotlib stuff going on. In Jupyter Notebook I always have to use the magic %matplotlib qt to switch backend in order to make it work. However, this might seem obvious to me, but others who're trying to work with my package this is not that straight forward.

This is what I have so far in my __init__.py:

def run_from_notebook():
    return hasattr(__builtins__, '__IPYTHON__')

if run_from_notebook():
     # this has no effect
    try:
        from IPython import get_ipython
        ipython = get_ipython()
    except ImportError:
        import IPython.ipapi
        ipython = IPython.ipapi.get()

    ipython.magic("matplotlib qt") 

I also tried:

if matplotlib.get_backend() != 'Qt5Agg':
    matplotlib.use('Qt5Agg')

but still no effect.

Is there a way to automatically switch backend in Jupyter Notebook when someone imports my package? and also: Is there any reason it's not considered as a good practice?

Péter Leéh
  • 2,069
  • 2
  • 10
  • 23

1 Answers1

0

It turns out that the problem is with the run_from_notebook function. When running it simply in a notebook cell it returns True, but when it's imported from my module, it returns False. The question now is rather: How to detect if code is run inside Jupyter?

For example running manually

def switch_backend_to_Qt5():
    import matplotlib
    if matplotlib.get_backend() != 'Qt5Agg':
        matplotlib.use('Qt5Agg')

gets the job done.

EDIT :

The following function suits my needs:

import os

def run_from_notebook():
    try:
        __IPYTHON__
        #  If it's run inside Spyder we don't need to do anything
        if any('SPYDER' in name for name in os.environ):
            return False
        # else it's probably necessary to switch backend
        return True
    except NameError:
        return False
Péter Leéh
  • 2,069
  • 2
  • 10
  • 23
  • 1
    some more solutions [here](https://stackoverflow.com/q/15411967/11305111) for checking if within a notebook – jayveesea Jun 03 '20 at 11:34