Luke Taylor Luke Taylor - 1 year ago 299
Python Question

PEP8 – import not at top of file with sys.path


PEP8 has a rule about putting imports at the top of a file:

Imports are always put at the top of the file, just after any module comments and docstrings, and before module globals and constants.

However, in certain cases, I might want to do something like:

import sys
sys.path.insert("..", 0)

import my_module

In this case, the
command line utility flags my code:

E402 module level import not at top of file

What is the best way to achieve PEP8 compliance with


I have this code because I'm following the project structure given in The Hitchhiker's Guide to Python.

That guide suggests that I have a
folder, separate from a
folder, both of which are in the same directory. If I want to access
, I think I need to add
to the

Answer Source

Often I have multiple files with tests in a subdirectory foo/tests of my project, while the modules I'm testing are in foo/src. To run the tests from foo/tests without import errors I create a file foo/tests/ that looks like this;

"""Path hack to make tests work."""

import os
import sys

bp = os.path.dirname(os.path.realpath('.')).split(os.sep)
modpath = os.sep.join(bp + ['src'])
sys.path.insert(0, modpath)

In every test file, I then use

import pathmagic

as the first import.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download