persisting data within a module

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Nov 14 06:57:19 CET 2007


En Tue, 13 Nov 2007 13:09:01 -0300, Peter J. Bismuti  
<peter.j.bismuti at boeing.com> escribió:

> How is that state different depending on whether a module has been simply
> imported (#2.  some other block of code has __name__ == "__main__") and  
> the
> script itself being run (#1. and having __name__=="__main__")?

It's not different at all, or I don't understand the question.

> Ultimately, what I want is for a module to remember (persist) the value  
> of A,
> regardless of how the module has been loaded into the interpreter.

It doesn't care. If you have a variable A in (the global namespace of) a  
module, it's there, no matter how the module has been loaded. A namespace  
has no concept of "history", it's just a mapping from names to objects.

Unless you're talking about this situation (should be on the FAQ, but I  
can't find it):

--- begin one.py ---
A = 1

if __name__=='__main__':
   print "In one.py, A=", A
   import two
   print "In one.py, after importing two, A=", A
--- end one.py

--- begin two.py ---
import one
print "In two.py, one.A=", one.A
one.A = 222
print "In two.py, after modifying one.A=", one.A
--- end one.py

Executing:

   >python one.py

you get this output:

In one.py, A= 1
In two.py, one.A= 1
In two.py, after modifying one.A= 222
In one.py, after importing two, A= 1

In this (pathological) case, there are TWO different instances of the  
one.py module, because modules are indexed by name in the sys.modules  
dictionary, and the first instance is under the "__main__" name, and the  
second instance is under the "one" name.
So: don't import the main script again.

-- 
Gabriel Genellina




More information about the Python-list mailing list