Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python can't find local module

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?

like image 253
apizzimenti Avatar asked Jul 01 '16 00:07

apizzimenti


People also ask

Why is Python not finding my module?

This is caused by the fact that the version of Python you're running your script with is not configured to search for modules where you've installed them. This happens when you use the wrong installation of pip to install packages.

Where does Python look for local modules?

Python looks for modules in “sys. It looks for a file called a_module.py in the directories listed in the variable sys. path .

Why do I need __ init __ py?

The __init__.py files are required to make Python treat directories containing the file as packages. This prevents directories with a common name, such as string , unintentionally hiding valid modules that occur later on the module search path.


1 Answers

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")
like image 159
Daniel Avatar answered Sep 21 '22 03:09

Daniel