8

I have a folder structure like this:

setup.py
core/
    __init__.py
    interpreter.py
tests/
    __init__.py
    test_ingest.py

If I try to import core in test_ingest.py and run it, I get an ImportError saying that the core module can't be found. However, I can import core in setup.py without an issue. My IDE doesn't freak out, so why is this error occurring?

apizzimenti
  • 427
  • 2
  • 7
  • 19

1 Answers1

13

When you import your package, Python searches the directories on sys.path until it finds one of these: a file called "core.py", or a directory called "core" containing a file called __init__.py. Python then imports your package.

You are able to successfully import core from setup.py because the path to the core directory is found in sys.path. You can see this yourself by running this snippet from your file:

import sys

for line in sys.path:
     print line

If you want to import core from a different file in your folder structure, you can append the path to the directory where core is found to sys.path in your file:

import sys
sys.path.append("/path/to/your/module")
Daniel
  • 2,345
  • 4
  • 19
  • 36
  • 1
    I've seen this solution quite frequently; in `test_ingest.py`, I have `sys.path.append("/Users/apizzimenti/Desktop/simple-engine-core/core")`. After this, I run `import core`, and an ImportError still follows. If I print the lines in `sys.path` after appending the path to the module, the path appears there. Even so, I get an ImportError. – apizzimenti Jul 01 '16 at 01:05
  • 3
    You want `sys.path.append("/Users/apizzimenti/Desktop/simple-engine-core/")` instead. You want to append the path to the directory in which `core` is found, not the path to the module itself. – Daniel Jul 01 '16 at 01:08
  • That works. Thank you! Now, for me to import `core` into other files in the `tests` module, do I have to append that path in every file? – apizzimenti Jul 01 '16 at 01:11
  • My pleasure! You could do that if you wanted to; alternatively, you could add the path to your `PYTHONPATH` environment variable. Check out this question: http://stackoverflow.com/questions/7472436/ – Daniel Jul 01 '16 at 01:23
  • I am on a mac and that answer mainly pertains to windows, but I added the path to the PYTHONPATH env variable and it all works out. Thank you for your help :) you are a gentleman and a scholar. – apizzimenti Jul 01 '16 at 01:29
  • Haha! Thank you very much; it's my pleasure. Good luck! – Daniel Jul 01 '16 at 01:32