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

Question:

I have a Python script 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?

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.

(I’m using Atom with linter-pylama.)

Asked By: Mausy5043

||

Answers:

The solution depends on the linter that is being used.

In my case I am using pylama

The manual for this linter suggests adding # noqa to the end of a line containing an error you wish to suppress.

Other linters may have different mechanisms.

Answered By: Mausy5043

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.

Answered By: BlackShift

Another, not so nice, solution, but one that I’ve temporarily deployed for an environment with matplotlib 1.0.0, is to use a wrapper module.

Inmatplotlib_agg.py:

import matplotlib
matplotlib.use('Agg')

In other files:

import matplotlib_agg
# other imports

Not sure whether this is worth it. I would prefer to ignore it in the editor; but I couldn’t get the one I use (PyCharm) to ignore just this one particular violation of PEP8 E402.

Answered By: BlackShift
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.