2

I have the following files:

./ElementExtractor.py
./test/ElementExtractorTest.py

In ElementExtractorTest.py, I am trying to import ElementExtractor.py like this:

import sys
sys.path.append('../')
import ElementExtractor

However, I am getting:

ImportError: No module named 'ElementExtractor'

How come it's not seen?

Is there a simple way to import another class with a relative reference?

martineau
  • 119,623
  • 25
  • 170
  • 301
bsky
  • 19,326
  • 49
  • 155
  • 270
  • Which version of Python are you using? How are you calling the `ElementExtractorTest.py` script exactly? Is it `python3 ./ElementExtractorTest.py` or is it `python3 ./test/ElementExtractorTest.py`? – Wojciech Walczak Jan 27 '18 at 18:06
  • 2
    I ssuggest that you read [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). – martineau Jan 27 '18 at 18:18
  • version is `3.5.1`. I'm just calling `python ./test/ElementExtractorTest.py` – bsky Jan 27 '18 at 18:18

2 Answers2

3

The general answer to this question should be don't, I guess. Messing with relative paths means that the path is relative to the place from where you're calling it. That's why PYTHONPATH is worth embracing instead.

Let's assume, your directory structure looks like this:

./projects/myproject/ElementExtractor.py
./projects/myproject/test/ElementExtractorTest.py

Now, you're calling your script like this:

[./projects/myproject]$ python3.5 ./test/ElementExtractorTest.py

Your current directory is myproject and in ElementExtractorTest.py you're adding ../ directory to sys.path. This means, that ./projects/myproject/../ (i.e.: ./projects) is effectively added to your PYTHONPATH. That' why Python is unable to locate your module.

Your code would work from test directory though:

[./projects/myproject/test]$ python3.5 ./ElementExtractorTest.py

Now, by adding .. to sys.path you are effectively adding ./projects/myproject/test/../ (i.e. ./projects/myproject) to sys.path, so the module can be found and imported.

Wojciech Walczak
  • 3,419
  • 2
  • 23
  • 24
-2

my folder structure

 ./test.py
 ./Data.py

from test.py

import Data
obj = Data.Myclass()

update

in your case

from ..ElementExtractor import MyClass

Hope this helps :)

Shiva Kishore
  • 1,611
  • 12
  • 29