views:

58

answers:

2

I have that file structure-

  1. Blog\DataObjects\User.py

  2. Blog\index.py

I want to import the function(say_hello) at User.py from index.py. I am trying this code -

from Blog.DataObjects.User import say_hello

say_hello()  

And I have that error -

Traceback (most recent call last):
  File "index.py", line 1, in <module>
    from Blog.DataObjects import User
ImportError: No module named Blog.DataObjects
+1  A: 
from DataObjects.User import say_hello
poke
+11  A: 

Python expects in every directory that should be importable, a file __init__.py, which may be empty. So, if you correct your file structure to this:

Blog/__init__.py
Blog/index.py
Blog/DataObjects/User.py
Blog/DataObjects/__init__.py

it should work, if the path to the directory is in your Python path (you can check this with:

import sys
print sys.path

). If not, mind that importing is done relative to the position of the current file. That is, since index.py is already inside Blog, the import should read:

from DataObjects.User import say_hello
Boldewyn
+1 for not being as lazy as I ;)
poke
Thank , It Worked!!
Yosy
@poke: :-) Thanks.
Boldewyn
@Yosy: You're welcome. By the way, you can accept one answer as the one answering the question. That's the small hook in the upper left corner of each answer, just below the number that tells the votes of other StackOverflow users.
Boldewyn