Reading Variables From Modules ?

Alex Martelli aleax at aleax.it
Tue Sep 11 05:42:05 EDT 2001


"Peter Moscatt" <pmoscatt at bigpond.net.au> wrote in message
news:i_jn7.36089$bY5.189269 at news-server.bigpond.net.au...
> I have a simple question - well to some I hope :-)
>
> If I was to have a module named MyModule.py which had a function like:
>
>         def TestNumber():
>                 A = 10
>                 return

This makes A a *LOCAL* variable of function TestNumber: A does
not even EXIST except inside TestNumber while TestNumber is
running.


> And I was importing this module into MyMain.py and then wanted to test the
> value of A in the imported module like:
>
>         import MyModule
>         if MyModule.A > 10 dosomething
>
> Obviously this dosen't work, so how is the best way to test the value of
> 'A' in the imported module ?

There is no value whatsoever of A in module MyModule, so there is
nothing to test.

If you want A to be a module-variable (aka global variable) of
module MyModule, you need to add a statement:
    global A
as the first statement of function TestNumber, so A will not be
a local variable of the funciton, but a module-level variable
(i.e. a "global" one).

You should also initialize A in the body of the module, so it
will have some value even if function TestNumber has not been
called yet.  Once that is done, then after "import MyModule"
you can indeed look at the value of MyModule.A.


Alex






More information about the Python-list mailing list