Jurudocs
Jurudocs

Reputation: 9165

Python import class simple example error

I wonder why my simple example building a class is not properly working:

The tree-structure looks like the following

class_project/
├── class_project
│   ├── __init__.py
│   └── classtheclass.py
└── tests 
    ├── __init__.py
    └── test.py

classtheclass.py looks like this:

class ClassTheClass(object):
    def __init__(self):
        print "yeees"

test.py looks like this:

from class_project.classtheclass import ClassTheClass


i = ClassTheClass()

While init.py are empty

so if i execute on the shell

python test.py

its giving me

Traceback (most recent call last): File "test.py", line 1, in from class_project.classtheclass import ClassTheClass ImportError: No module named class_project.classtheclass

Whats wrong with that. In Pycharm this even works...!

Upvotes: 0

Views: 92

Answers (3)

kumarprd
kumarprd

Reputation: 936

Your file tree structure is wrong, if you are not exporting PYTHONPATH with the new lib path, you have to put the test.py as below structure to make the test.py to access classtheclass from class_project.

class_project/
├── class_project
│   ├── classtheclass.py
│   └── __init__.py
└── test.py

Upvotes: 1

fatelei
fatelei

Reputation: 164

Python search imported module as follow, for example import foo

  • Firstly, search the built-in module, If foo isn't a built-in module, go to next
  • Interpreter will search the sys.path, sys.path will include: current directory, PYTHONPATH and installation dependent path. If foo is in sys.path, it will be imported. Otherwise, it will be ImportError.

Here, you can execute at project parent directory or explicit add /path/to/project to sys.path.

Upvotes: 0

Thomas Orozco
Thomas Orozco

Reputation: 55207

When you run python test.py, the interpreter will look for Python code in standard library locations (e.g. /usr/local/lib/python2.7/site-packages and friends) and in the tests folder where you invoked the interpreter (this set of locations is known as the "Python Path", and you can view it with: import sys; print sys.path).

None of those locations include class_project.classtheclass.

There are a variety of ways to solve this problem.

You can set the PYTHONPATH environment variable to include class_project:

export PYTHONPATH="/path/to/class_project:$PYTHONPATH"  # Note: this has to be the top-level class_project directory, you have two with this name here.
python test.py  # This will now work

You could probably also use a relative import, but I'd argue that's working around the problem not solving the problem.

Upvotes: 1

Related Questions