Concerned_Citizen
Concerned_Citizen

Reputation: 6845

Cannot Import Class in Python

I have the following project skeleton.

ex47 
    bin/
    docs/
    ex47/
        __init__.py
    tests/
        __init__.py
        game_tests.py
    game.py
    setup.py

Working on Aptana Studio. In game_tests.py I have

from nose.tools import *
from ex47.game import Room

but Aptana is yelling at me for not being able to find Room, which I defined in 'game.py' as a class. When I run nosetests on command line I got Error: Import Error( no module named game). What's seems to be wrong?

Upvotes: 0

Views: 1541

Answers (1)

kgr
kgr

Reputation: 9958

I see two issues:

  • topmost ex47 is not a valid package (there is no __init__.py)
  • topmost ex47 is not on your PYTHONPATH

The first one is obvious. If you want game.py to be importable using ex47.game then ex47 has to be a valid package. So most probably you wanted to put it in the inner ex47 which is a valid package?

When it comes to the second issue, python will look for ex47 on your PYTHONPATH and in the current directory (the one you are in when issuing commands). Probably none of those is the case, hence ex47 can't be found.

Considering the above, if you had the following directory structure:

ex47 
    bin/
    docs/
    ex47/
        __init__.py
        game.py
    tests/
        __init__.py
        game_tests.py
    setup.py

and tried to run tests like this:

nosetests tests

while being in the topmost ex47 directory it should work (note that there is no __init__.py inside the topmost ex47).

Upvotes: 5

Related Questions