Reading Variables From Modules ?
Peter Hansen
peter at engcorp.com
Tue Sep 11 06:34:29 EDT 2001
Peter Moscatt wrote:
>
> If I was to have a module named MyModule.py which had a function like:
>
> def TestNumber():
> A = 10
> return
>
> 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 ?
Change MyModule.py to be like this:
def TestNumber():
global A
A = 10
return
Note that this would mean A does not exist until TestNumber()
is called for the first time. Therefore the code in MyMain.py
as you have written it would not work. If you are more
interested in MyMain.py working as is, make MyModule.py look like
this:
A = 10
:)
On the other hand, global variables are something to be avoided
more often than not, and overuse of them will lead to your
program being buggy and unmaintainable. There may be alternative
ways to structure your code which would avoid some of these
issues, including wrapping things in an object-oriented fashion.
--
----------------------
Peter Hansen, P.Eng.
peter at engcorp.com
More information about the Python-list
mailing list