NameError in cross imports of modules

Pearu Peterson pearu at cens.ioc.ee
Sat Feb 3 14:31:01 EST 2001


Hi!

I have two classes defined in separate files and both classes use each
other:

File A.py:
  from B import *
  class A:
      def asB(self): return B()

File B.py:
  from A import *
  class B:
      def asA(self): return A()

In Python session I get NameError:

>>> from A import *
>>> from B import *
>>> B().asA()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "B.py", line 5, in asA
    return A()
NameError: global name 'A' is not defined

but

>>> A().asB()
<B.B instance at 0x810ea4c>


Note: I am not interested in converting the 'from-import' statements to
'import' statements, rather I have collected the classes A and B into the
same file but it's really inconvenient to maintain a large package in one
file :(


This behavior is well-known and has, roughly speaking, the following
explanation:
>>> from A import *    --- imports also module B but only "partly": module
                           A is not imported to module B.
>>> from B import *    --- nothing is done because module B is already in
                           sys.modules.

>>> reload(sys.modules['B'])  --- is needed in order to fix the
                           NameError: module B will be imported
                           "completely".

My question is: 
	could this reload be done automatically? 

Say, when module B is "partly" imported during `from A import *', then a
flag is set. This flag is used when one imports module B: instead of
doing nothing when it is already in sys.modules, module B will be reloaded
and the flag will be unset.

What do you think? Is is possible to get rid of this asymmetric behavior
of cross imports in future Python releases?

Pearu






More information about the Python-list mailing list