Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python "ImportError: No module named...", but the module exists

My file directory tree looks like this:

my_repo
├── experiments
│   ├── foo.py
│   └── __init__.py
└── tests
    ├── baz.py
    └── __init__.py

Inside baz.py, I try

from experiments.foo import FooExperiment

but I get

*** ImportError: No module named experiments.foo

When I open python from the terminal (Mac OSX 10.9) and run

from experiments.foo import FooExperiment

the class is imported properly. What is going on? Please help.

In both situations the sys.path is exactly the same, except when I'm in baz.py the current path (to baz.py) is included. And yes /path/to/my_repo is in my sys.path as well.

EDIT: my issue was with conflicting egg files, so reinstalling did the trick (below). Accepting @Austin Marshall's answer though because it's a viable solution to the general case of this problem.

pip uninstall my_repo
python setup.py develop --user
like image 548
BoltzmannBrain Avatar asked Nov 22 '22 05:11

BoltzmannBrain


1 Answers

experiments is not in PYTHONPATH, nor is it installed using the standard setuptools technique. I'm able to replicate your problem, which is resolved by putting my_repo in PYTHONPATH:

Austins-MacBook-Pro-2:my_repo amarshall$ tree .
.
├── experiments
│   ├── __init__.py
│   └── foo.py
└── tests
    ├── __init__.py
    └── baz.py

2 directories, 4 files
Austins-MacBook-Pro-2:my_repo amarshall$ PATH=$PATH:`pwd`/experiments python tests/baz.py 
Traceback (most recent call last):
  File "tests/baz.py", line 1, in <module>
    from experiments.foo import FooExperiment
ImportError: No module named experiments.foo
Austins-MacBook-Pro-2:my_repo amarshall$ PYTHONPATH=$PYTHONPATH:`pwd` python tests/baz.py 

Where there's no output, or error in the last line when PYTHONPATH is specified, rather than PATH

like image 200
Austin Marshall Avatar answered Feb 01 '23 13:02

Austin Marshall