Load a module twice ... or not ???

Gordon McMillan gmcm at hypernet.com
Tue Mar 21 14:16:04 EST 2000


Philip Payne writes:

> Can anyone by any chance give me a definitive explanation to the
> following (Python 1.5.2).
> 
> In the book 'Internet Programming with Python', by Watters, van Rossum
> and Ahlstrom, in the section 'How to Load a Module Twice, and Why You
> Shouldn't', on page 199/200 (my edition, anyway), it states that you
> shouldn't  have module interrelationships that result in a module
> running as a main program and also being imported by another module in
> the same interpreter. 

Here's the simple example:
--module A
import B
a = 1
if __name__ == '__main__':
  global a
  a = 2
  B.doit()
--module B
import A
def doit():
  print A.a
---------
If you run A, it will print "1".


> Since I don't, in practice, encounter any problems doing what WvRA say I
> shouldn't do, is this in fact an issue? Is the above quote relevant to
> current Python versions?? And if so, can someone tell me in detail under
> what circumstances there might be a problem?

Yes (you're lucky); yes; see above.

- Gordon




More information about the Python-list mailing list