[Tutor] Global Variables between Modules ??
Tue Nov 5 13:28:06 2002
At 21:10 2002-11-05 +1300, Graeme Andrew wrote:
>I know this is bad programming practice but I am desperate to set a global
>variable that can be shared between modules.
You can't to that. But you can use whatever module
you like to store it in.
shared.value = 'Hello'
Python 2.2.1 (#34, Sep 27 2002, 18:37:42) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import writeshared
>>> import readshared
The four byte file shared.py can basically be seen as a
free form non-persistent database here. :) Watch the power
of dynamic programming! As usual, you are driving without
any seat belts. It's up to you to make sure that you don't
overwrite anything or make any mistake about assumed types,
existing values etc.
Putting "value = ''" in shared.py might be an indicator
for its use, and will prevent an attribute error if it's
read before it's written. If that's what you want...
>I have a TKinter class module
>that had a 'get' method to return what button was pushed. I want to store
>the result of that 'get' call in a global variable that is accessable to all
>the modules in the application. (the TKinter class is destroyed immediately
>after the 'get' method is called)
A more conventional and OO approach might be that a longer
lasting class instance is responsible for shoving up the
dialog that asks the questions, and that the dialog returns
this value, which is then stored as an attribute in the
calling class. The calling class would then pass either this
attribute or self to those who need to access it.
>As I undestand it the key word 'global' only pertains to the module it is
>used in ??
>Any other ideas ? Would importing a 'global module' that has global
>variables be the correct path to follow ??
I guess you mean what I showed above. Obviously it works. How do
you mean "correct"? If you mean "politically correct", it depends
on your political colour. ;) You are keeping the data confined in
a particular name space at least. On the other hand, someone who
inspects "sharedpy" might be confused--unles he is used to this
idiom, in which case it will seem normal...
If you overuse such a namespace, you will end up with a bad spaghetti
structure that makes your program difficult to maintain. Whatever
keeps the program as simple as possible is good. It's dificult to
know what this might be. Some ways of working are excellent in small
systems, but can't scale. Others are useful in large systems but
overkill in simple apps.
Am I confusing you? Maybe you should study more zen... ;)
Magnus Lycka, Thinkware AB
Alvans vag 99, SE-907 50 UMEA, SWEDEN
phone: int+46 70 582 80 65, fax: int+46 70 612 80 65