Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"ImportError: No module named" error doesn't seem to be related to my code

I am trying to complete Exercise 47 of Learn Python The Hard Way, 2nd Edition, but I am receiving this error when I run tests/ex47_tests.py:

File "tests/ex47_tests.py", line 3, in <module>
    from ex47.game import Room
ImportError: No module named ex47.game

I thought it was something I was doing wrong within my code because I am very new at this, so I cloned this repo from a GitHub user who seems to have successfully completed the exercise.

Not only are the relevant parts of our code identical, but I receive the same error when I try to run the tests/ex47_tests.py that I cloned from him. So now I am lost and hoping that someone has a solution for me. Any ideas?

like image 325
Corey Avatar asked Dec 21 '22 09:12

Corey


1 Answers

fabrizioM's answer should get it to work. Here is a little explanation.

When Python loads a file, it searches on the filesystem. So here, we have the import statement:

from ex47.game import Room

It looks for the file ex47.py on the modules search path (accessible as sys.path in Python code). The modules search path contains some directories based on the installation details of Python, the directories listed in the PYTHONPATH environment variable, and contains the parent directory of the script you’re executing. It doesn't find ex47.py on the path, but it sees there is a directory named ex47 with __init__.py inside of it. It then finds game.py in that folder.

The problem is that your current folder is not on the modules search path. Because ex47_tests.py was run, it has $cwd/tests on the path. You need $cwd on the path.

PYTHONPATH=. python tests/ex47_tests.py

does exactly that. It puts the $cwd on the modules search path so Python can find the source files.

You can also do:

python -m tests.ex47_tests

This will run it as a module instead of a file, while it will use the current directory as path it adds automatically to the the modules search path instead of the directory the file is located inside.

like image 60
Jonathan Sternberg Avatar answered Dec 24 '22 03:12

Jonathan Sternberg