persisting data within a module

Gabriel Genellina gagsl-py2 at
Wed Nov 14 06:57:19 CET 2007

En Tue, 13 Nov 2007 13:09:01 -0300, Peter J. Bismuti  
<peter.j.bismuti at> 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 ---
A = 1

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

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



you get this output:

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

In this (pathological) case, there are TWO different instances of the 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