Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add path to sys.path vs. PEP E402

In order to import a project specific module somewhere located on your disk, one can easily append this directory to sys.path:

import sys
sys.path.append(some_module_path)

import some_module

However, the latter import now violates PEP E402 ("module level import not at top of file"). At least spyder tells me so. Is spyder here too picky?

In spyder there is the principal idea of a "project", where I assumed environments can be adjusted specific for this project. However, I have no clue, how to modify e.g. the sys.path depending on a spyder project.

How can I modify sys.path in a spyder project? Or is there a general python way of solving this issue?

like image 398
Sosel Avatar asked May 17 '19 10:05

Sosel


People also ask

How do I add path to SYS path?

append(mod_directory) to append the path and then open the python interpreter, the directory mod_directory gets added to the end of the list sys. path. If I export the PYTHONPATH variable before opening the python interpreter, the directory gets added to the start of the list.

Is SYS path append bad?

Most of the time, appending to sys. path is a poor solution. It is better to take care of what your PYTHONPATH is set to : check that it contains your root directory (which contains your top-level packages) and nothing else (except site-packages which i).

When should I use sys path append?

The sys. path. append() method is used to append the path that we want to the existing list.

What is SYS path append (' ')?

Python sys path append() The sys. path. append() is a built-in function of the sys module in Python that can be used with path variables to add a specific path for an interpreter to search.


2 Answers

You could put the sys.path extension in a separate module, e.g. _paths.py.

Contents of _paths.py:

import sys

sys.path.append(some_module_path)
sys.path.append(some_other_module_path)
# ...and so on...

And then in your main application:

import sys

import _paths
import some_module

some_module.some_func()

This solution puts your "project configuration" nicely in a single place (which makes it easy to maintain in the future), and complies with at least PEP8 (including E402) and pylint rules.

like image 83
wovano Avatar answered Sep 27 '22 01:09

wovano


As alternative solution to the answer with a separate module if found this as working solution for me.

try:
    sys.path.append(Path(__file__).parent.parent)
except IndexError:
    pass

If I just use the sys.path.append(...), I get the warning, but using the try-catch block does not produce a warning.

like image 34
FreshD Avatar answered Sep 23 '22 01:09

FreshD