persisting data within a module
davisn90210 at gmail.com
davisn90210 at gmail.com
Mon Nov 12 23:30:56 EST 2007
On Nov 12, 5:30 pm, "Peter J. Bismuti" <peter.j.bism... at boeing.com>
wrote:
> I'm having trouble understanding how namespaces work in modules. I want to
> execute a module within the interpreter and then have values that are
> calculated persist so that other modules that get executed can retrieve them.
>
Modules retain state their state across all imports in the same
interpreter instance. Module state is not shared among different
instances of the interpreter.
> For example, consider the two simple modules below. The first method fails
> and I'm not sure exactly why. (Note: assume one instance of an interpreter.
> In my case a 3rd party software tool that starts an interpreter when it
> launches).
>
> Two alternate ways of running it:
>
> 1. (FAILS: RESULTS A = 0) Use the module "test" itself as the driver using
> the conditional statement if (__name__=="__main__"):
>
> test.py
> run2.py
>
Ok, what do you mean by this? Do you mean run test.py and then run
run2.py? In so, then you will have *two* instances -- one for each
file being executed. You can only have one main module per
interpreter instance. I suspect this is the source of your confusion.
> or,
>
> 2. (SUCCES: RESULTS A = 10) Use "run.py" as the driver.
>
> run.py
>
> _________test.py__________________
>
> import sys,os
>
> A = 0
>
> def getA():
> global A
> return A
>
> def run():
> global A
> A = 10
>
> if (__name__=="__main__"):
> run()
>
Here, A is only initialized when the module is loaded iff it is the
main module. If it's not the main module, then it will have A set to
0 until some other code calls run().
> _________run.py__________________
>
> import test
>
> test.run()
> print "A = " + str(test.getA())
>
This code calls test.run(), which is necessary for A to be 10.
> _________run2.py__________________
>
> import test
>
> print "A = " + str(test.getA())
>
> --
>
This code gets the value of test.A without calling test.run(). Since
test.run() was not called, A is the value it was initialized when the
test module was loaded -- namely, 0.
Hope this helps,
--Nathan Davis
More information about the Python-list
mailing list