0

Sure this is a newbie and common error, but I could no find a solution because I don't know the name of this kind of issues.

I've got 2 python files p1.py and p2.py

p1.py:

from p2 import *

def a():
  print "Caller a --> Calling b"
  b()

def c():
  print "Caller c --> Calling d"
  d()

a()

p2.py:

from p1 import *

def b():
  print "Caller b --> Calling c"
  c()

def d():
  print "Caller d --> END"

When I run p1.py I get next error:

NameError: global name 'b' is not defined

What I'm doing wrong? Any recommended [short] read?

DirtyBit
  • 16,613
  • 4
  • 34
  • 55
Carol
  • 553
  • 2
  • 10
  • 24

2 Answers2

1

You have a Python Circular Imports problem.

A possible fix:

p1.py:

def a():
  print("Caller a --> Calling b")
  import p2
  p2.b()

def c():
  print("Caller c --> Calling d")
  import p2
  p2.d()

a()

py2.py

def b():
  print("Caller b --> Calling c")
  import p1
  p1.c()

def d():
  print ("Caller d --> END")

and:

py -m p1.py

OUTPUT:

Caller a --> Calling b

Caller b --> Calling c

Caller a --> Calling b

Caller b --> Calling c

Caller c --> Calling d

Caller d --> END

Caller c --> Calling d

Caller d --> END

Process finished with exit code 0

Community
  • 1
  • 1
DirtyBit
  • 16,613
  • 4
  • 34
  • 55
1

Yeah, the circular imports.

Now the [short] read (example to understand your example)

p1.py:

from p2 import *

print "p1"

p2.py:

from p1 import *

print "p2"

When you run p1.py, the output is:

p1
p2
p1

What does it mean?

p1 - the first line 'from p2 import *' imports p2, and p2 in turn launches 'from p1 import *', so p1 is determined (note: p2 is not determined yet, and this is the reason of NameError: global name 'b' is not defined in your example)

[import of p1 is finished]

p2 - now lines after the import in p2

[import of p2 is finished, now return to p1]

p1 - now lines after the import in p1

Litvin
  • 330
  • 1
  • 9