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

pnpayne at swissonline.ch pnpayne at swissonline.ch
Tue Mar 21 16:09:29 EST 2000


Gordon McMillan wrote:

> 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".

Gordon, the example may be simple but with global variables you are really
having to try quite hard. I don't write code that does anything like this. All
I do is have a module A.py that might be:
  def f1(): ...
  def f2(): ...
  class C1: ...
  def main():
     c = C1()
     c.GO()
  if  __name__ == '__main__' : main()
that runs as a main program in the PyApache-embedded interpreter. Then I have
another module B.py that imports A just in order to use the function f1()
defined there. B.py might be:
  import A
  def f3(): ...
  class C2: ... includes references to A.f1() ...
  def main():
     c = C2()
     c.GO()
B also runs as a main program in the same interpreter 'session' as A did,
since I don't kill the interpreter between Apache requests, but I really don't
see why I should have any problems. All the examples I've seen so far involve
global variables in one form or another.  I don't use global variables except
for performance reasons to cache database data between Apache requests and
these globals are only set once. What mystified me in WvRA's book was the
references to classes being defined twice. I mean, so what if they are???

>
>
> > 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