Reading Variables From Modules ?

Peter Moscatt pmoscatt at bigpond.net.au
Tue Sep 11 06:48:26 EDT 2001


Alex & Pete,

Thanks for the replys.  Yep, I tried it and all is well.

Is this the best way to handle transfers like this or is there a prefered 
method ?

Pete


Peter Hansen wrote:

> 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.
> 




More information about the Python-list mailing list