user3591079
user3591079

Reputation: 293

Importing from parallel directories with python 2.7

I have recently started working on a project and have been tasked with implementing some new features as well as unit testing for those features. I have been trying to import modules into the unit testing file but when I run it I come across an ImportError: No module named Developing.algorithms when I try to import into test_algorithms.py

I have tried importing with both

from Developing import algorithms as algo

and

import Developing.algorithms as algo

My structure is similar to this Testing project that I made:

Testing/
    __init__.py
    Developing/
        __init__.py
        algorithms.py
    Master (Stable)/
    Tests/
        __init__.py
        test_algorithms.py

And I run into:

ImportError: No module named Developing.algorithms

Or when I change the import to: from Developing import algorithms

ImportError: No module named Developing

I have read many similar questions and from those I have learned to include init.py files into each directory that has a file that I want to import. I currently do not have any errors according to PyCharm but when I run it from terminal I run into that import error. I also do not want to modify the system / python path as I read that everyone that uses the project would have to so the same. So how can I import from parallel directories without changing paths?

Upvotes: 1

Views: 810

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 90929

You will need to add the directory Testing into your PYTHONPATH env variable, to be able to import Developing.algorithms directly (or the directory above Testing to be able to import Testing.Developing.algorithms ).

In windows, you can set the PYTHONPATH variable as -

set PYTHONPATH=\path\to\Testing\;%PYTHONPATH%

In Bash , you can try -

export PYTHONPATH=/path/to/testing/:$PYTHONPATH

Programatically (from python) , you can do the following before you try to import Developing.algorithms -

import sys
sys.path.append('/path/to/Testing/')
from Developing import algorithms # or how ever you want to import.

Also, you do not need to do all of the above, any one would do - either setting PYTHONPATH env variable, or using sys.path .

Upvotes: 3

Related Questions