0

SO pyton gurus! I've just found an astonishing phenomenon that I don't understand. The problem can be best shown as code:

#== kid.py ==#
import dad

def spam ():
    dad.spam()


#== dad.py ==#
import kid

x = 1
print "body", x

x = 2
def spam ():
    print "spam", x

if __name__ == '__main__':
    x = 3
    spam()
    kid.spam()
    print "main", x

I'm using Python 2.7.3. Can you guess the output of python dad.py? The answer is (I wish SO had a spoiler shading tag) body 1 body 1 spam 3 spam 2 main 3. So could you explain

  1. Why is body 1 printed twice?
  2. How can dad.x != kid.dad.x be?
  3. If I really need to make the two modules import each other, how can I modify it to get kid.dad.x properly updated?
Charles
  • 50,943
  • 13
  • 104
  • 142
h2kyeong
  • 447
  • 3
  • 13

1 Answers1

4
  1. Because loading dad.py as the __main__ module is independent of importing dad.py as the dad module.
  2. See my answer to 1.
  3. Import __main__ instead if you must. But in general, don't try this. Find another way to accomplish your tasks (e.g. classes).

Printing __name__ at the top of dad.py will illustrate this.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358