9

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?

1 Answer 1

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") 
Sign up to request clarification or add additional context in comments.

6 Comments

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.
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.
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?
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: stackoverflow.com/questions/7472436
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.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.