[Tutor] Re: import problem (Chad Crabtree)

pan at uchicago.edu pan at uchicago.edu
Mon May 10 22:04:41 EDT 2004


> --- pan at uchicago.edu wrote:
> > Hi,
> > 
> > I wanna import a class MyClass from a module
> > myModule.py but something
> > weird just happened :
> > 
> > [1] import myModule   ===> ok
> > 
> > [2] from myModule import * ===> ok
> > 
> > [3] from myModule import MyClass ===> ImportError:
> > cannot import name MyClass
> > 
> > [4] But when I put [3] inside a class:
> > 
> >     class NewClass(object):
> >       def __init__(self):
> >          from myModule import MyClass    # <======= 
> >          self.item = MyClass()
> >   
> >     x = NewClass()
> >     print x.item.__doc__
> > 
> >     ===> THIS IS OK !!!
> > 
> > How come a class can't be imported when the
> > statement:
> > "from myModule import MyClass" is placed globally,
> > but 
> > no problem at all when it is inside a class ????
>
> Investigate a little.  You should at the interactive
> prompt type import myModule 
> then type dir(myModule) and see if your class is
> there.  If not then something strange has happend I'm
> sure.  In addition when you do this paste a traceback
> of the error.

Thx for who replied. I found a solution to fix the problem (although I 
still can't fully explain some weird behaviors). In myModule, there's a 
function 'cgiBrowser' placed BEFORE the class definition of MyClass. 
That function has error in some circumstances, resulting in a termination 
of myModule loading. After modifying that function, the problem is gone. 

The funny thing (before the problem was corrected) is, when the 
test_MyClass is executed the first time, it returns:

>>> 
Traceback (most recent call last):
  File "C:\Python22\Lib\site-
packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript
    exec codeObject in __main__.__dict__
  File "D:\Pan\PC\Prog\lang\py\cgi\test_MyClass.py", line 8, in ?
    from myModule import MyClass
  File "D:\Pan\PC\Prog\lang\py\cgi\myModule.py", line 6, in ?
    from test_MyClass import cgiBrowser     #<========================== [a]
  File "D:\Pan\PC\Prog\lang\py\cgi\test_MyClass.py", line 8, in ?
    from myModule import MyClass
ImportError: cannot import name MyClass

But if it is executed from the 2nd time and beyond, it returns:

>>> 
Traceback (most recent call last):
  File "C:\Python22\Lib\site-
packages\Pythonwin\pywin\framework\scriptutils.py", line 301, in RunScript
    exec codeObject in __main__.__dict__
  File "D:\Pan\PC\Prog\lang\py\cgi\test_MyClass.py", line 8, in ?
    from myModule import MyClass
ImportError: cannot import name MyClass

Note that at the first time it reports the error @ cgiBrowser (marked as
line [a] ), but since then more executions only report that it can't import 
the class MyClass. 



More information about the Tutor mailing list