Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python importing a module from a parallel directory

Tags:

How would I organize my python imports so that I can have a directory like this.

project |      \ |      __init__.py |      src |   \ |    __init__.py |    classes.py | test     \      __init__.py      tests.py 

And then inside /project/test/tests.py be able to import classes.py

I've got code looking like this in tests.py

from .. src.classes import(     scheduler     db ) 

And am getting errors of

SystemError: Parent module '' not loaded, cannot perform relative import 

Anyone know what to do?

like image 681
Zack Avatar asked Jul 08 '14 00:07

Zack


People also ask

How does Python import modules from some other directory?

We can use sys. path to add the path of the new different folder (the folder from where we want to import the modules) to the system path so that Python can also look for the module in that directory if it doesn't find the module in its current directory.

Can import Python file from same directory?

Make an empty file called __init__.py in the same directory as the files. That will signify to Python that it's "ok to import from this directory". The same holds true if the files are in a subdirectory - put an __init__.py in the subdirectory as well, and then use regular import statements, with dot notation.

How do I import a module from the outside directory?

Method 1: Using sys. The sys. path variable of the module sys contains the list of all directories in which python will search for a module to import. We can directly call this method to see the directories it contains. So for importing mod.py in main.py we will append the path of mod.py in sys.


1 Answers

Python adds the folder containing the script you launch to the PYTHONPATH, so if you run

python test/tests.py 

Only the folder test is added to the path (not the base dir that you're executing the command in).

Instead run your tests like so:

python -m test.tests 

This will add the base dir to the python path, and then classes will be accessible via a non-relative import:

from src.classes import etc 

If you really want to use the relative import style, then your 3 dirs need to be added to a package directory

package * __init__.py * project * src * test 

And you execute it from above the package dir with

python -m package.test.tests 

See also:

  • https://docs.python.org/2/using/cmdline.html
  • http://www.stereoplex.com/blog/understanding-imports-and-pythonpath
like image 90
Peter Gibson Avatar answered Sep 21 '22 16:09

Peter Gibson