Import Problems

Bill Jackson jackson at hotmail.com
Fri Apr 27 15:49:39 EDT 2007


Once again, I am having issues with imports...

Until now, I thought the general guidelines were to rarely use 'from x 
import y' syntax, except when you really want to copy names over. 
However, I have run into issues by following this guideline.  So...

1) What is going wrong in the example below?
2) What is a good way to handle imports for packages w/subdirectories?

Here is a sample directory structure:

importtest/
   __init__.py
   test2/
     __init__.py
     someclass.py
     mytest.py


Here are the definitions of the files:

# importtest/__init__.py
from test2 import *

# importtest/test2/__init__.py
from someclass import *
from test2 import *

# importtest/test2/someclass.py
class SomeClass:
    pass

# importtest/test2/mytest.py
import importtest
print importtest.SomeClass


On import I get the following:

 >>> import importtest
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/home/user/lib/python/importtest/__init__.py", line 1, in ?
    from test2 import *
  File "/home/user/lib/python/importtest/test2/__init__.py", line 2, in ?
    from mytest import *
  File "/home/user/lib/python/importtest/test2/mytest.py", line 3, in ?
    print importtest.SomeClass
AttributeError: 'module' object has no attribute 'SomeClass'
 >>>


The problem seems to be an 'order' issue.  importtest/test2/__init__.py 
has loaded someclass.py, but it doesn't seem to have copied its contents 
into importtest/__init__.py....perhaps it is because it hasn't finished 
all of its imports.  Is this correct?

So what is a good way to deal with this?  In files which contain 
implementations, I thought it was best not to use 'from x import y', but 
this seems to be the only way to get this to work:

# importtest/test2/mytest.py
from someclass import SomeClass
print SomeClass

Is this the guideline?
   Use 'from x import y' for modules within your package.
   Use 'import y' for modules outside your package.

Help.



More information about the Python-list mailing list