Strange import behavior

Peter Otten __peter__ at web.de
Fri Sep 1 19:44:14 CEST 2006


unexpected wrote:

> Hey guys,
> 
> I'm having problems importing a file into my python app. Everytime I
> try to define the object specified by this file, i.e,
> 
> test = Test(),
> 
> It raises an ImportError exception: ImportError: cannot import name
> Test.
> 
> I've declared it as:
> 
> from test import Test (and I've also tried from test import *)
> 
> As luck would have it, if I try creating a newfile (say test2) and then
> declare the same class as:
> 
> from test2 import Test()
> 
> It works fine! I tried doing this with the first couple of files, but
> then another error crops up for another file giving me this
> ImportError...so I'd end up having to re-copy a bunch of files over
> again.
> 
> I feel like there may be some sort of dependency screw up or
> whatever..Is there a command that's like "Python, chill, let's start
> from scratch and build this thing"?

Replace

from test import Test

with

import test
print test.__file__
raise SystemExit

The test file you are importing is probably not the one you expect. To fix
that make sure that the directory of /your/ test.py is in sys.path /before/
the directory of the test file you are accidentally importing. Even better,
rename it to something unambiguous as the name 'test' is already taken by
the test package of a vanilla Python installation. For example, I get

>>> import test
>>> test.__file__
'/usr/local/lib/python2.4/test/__init__.pyc'

The ImportError is actually an AttributeError in disguise:

>>> import test
>>> test.Test
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: 'module' object has no attribute 'Test'
>>> from test import Test
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
ImportError: cannot import name Test

Peter




More information about the Python-list mailing list