1

For example, I have the following source files: file a.py

from b import *

def A():
    print 'function A'
    B()
    return

file b.py

from a import *

def B():
    print 'function B'
    A()
    return

def main():
    A()
    B()
    return

if __name__ == '__main__':
    main()

Then I run python b.py, I met with the following error:

NameError: global name 'A' is not defined

The full message, together with prints is as follows:

function A
function B
Traceback (most recent call last):
  File "b.py", line 14, in <module>
    main()
  File "b.py", line 9, in main
    A()
  File "/home/mypath/a.py", line 5, in A
    B()
  File "/home/mypath/b.py", line 5, in B
    A()
NameError: global name 'A' is not defined

What's wrong with it? Thank you all for helping me!

luoluo
  • 5,353
  • 3
  • 30
  • 41
pfc
  • 1,831
  • 4
  • 27
  • 50
  • You have `circle` import problem – luoluo May 20 '17 at 02:35
  • @luoluo Is it not allowed? – pfc May 20 '17 at 02:36
  • 1
    @pfc Not in Python, no. When you import a module, all of the code in that module is run. A imports B which imports A which imports B which imports... – MackM May 20 '17 at 02:41
  • @MackM Wrong. Circular imports *are* allowed in Python and work with careful programming. I have done it. Idlelib has circular imports, but careless movements of imports can disable IDLE. If sys.modules['a'] does not exist, `sys.modules['a'] = new_module()` is done first. Then the code in a.py is executed to fill in the module. If a.py has an import statement, then the execution of a.py is interrupted by a recursive call to the internal import function. If every recursive call returns, then the circular imports are ok. – Terry Jan Reedy May 20 '17 at 03:06

0 Answers0