8

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?

Sosel
  • 1,678
  • 1
  • 16
  • 31

3 Answers3

7

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.

wovano
  • 4,543
  • 5
  • 22
  • 49
3

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.

FreshD
  • 2,914
  • 2
  • 23
  • 34
1

I know this doesn't answer the question, but it may be helpful information.

You can import that module by directly specifying its path, without using sys.path.append

In Python 3 this is as simple as

import imp
some_module = imp.load_source('some_module', '/path/to/some_module.py')

More information here: How to import a module given the full path?

Daniel F
  • 13,684
  • 11
  • 87
  • 116
  • True. But please don't do this as a work-around for the problem mentioned in the question! Changing PYTHONPATH or ignoring the PEP warning for this specific scenario is a much better solution! – wovano May 17 '19 at 10:44
  • My issue with modifying PYTHONPATH as a general solution is that it affects all the scripts run by a user, unless you use `FOO=bar somecommand someargs` or some sort of virtualization. – Daniel F May 17 '19 at 10:51
  • I agree. I would create a batch file to setup the PYTHONPATH then, but I don't really like that solution as well. See my [answer](https://stackoverflow.com/a/56185125/10669875) for a nicer solution :-) – wovano May 17 '19 at 11:05
  • @wovano nice solution, indeed! – Daniel F May 17 '19 at 11:08