Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

matplotlib.use required before other imports clashes with pep8. Ignore or fix?

I have a pythonscript that starts like this:

#!/usr/bin/env python
import matplotlib
matplotlib.use("Agg")

from matplotlib.dates import strpdate2num
import numpy as np
import pylab as pl
from cmath import rect, phase

It works like a charm, but my editor complains: E402 module level import not at top of file [pep8].

If I move the matplotlib.use("Agg") down, the script will not work.

Should I just ignore the error? Or is there a way to fix this?

EDIT : I'm aware that PEP8 says that this is only a suggestion and it may be ignored, but I'm hoping that there exists a nice way to initialise modules without breaking PEP8 guidelines, as I don't think I can make my editor ignore this rule on a per-file-basis.

EDIT2 : I'm using Atom with linter-pylama

like image 573
Mausy5043 Avatar asked Sep 03 '16 10:09

Mausy5043


1 Answers

Apparently, matplotlib now has a switch_backend() function:

import matplotlib.pyplot
# import other modules
matplotlib.pyplot.switch_backend('Agg')

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.switch_backend

But beware, you run the risk of exploding:

Switch the default backend. This feature is experimental, and is only expected to work switching to an image backend. e.g., if you have a bunch of PostScript scripts that you want to run from an interactive ipython session, you may want to switch to the PS backend before running them to avoid having a bunch of GUI windows popup. If you try to interactively switch from one GUI backend to another, you will explode.

Calling this command will close all open windows.

It works nicely for me with matplotlib 1.3.1 but not with 1.0.0.

like image 75
BlackShift Avatar answered Sep 23 '22 01:09

BlackShift