Global variables..

Jeff Shannon jeff at ccvcorp.com
Mon Oct 25 19:50:25 EDT 2004


Ishwar Rattan wrote:

>Say I have two pythom modules in separate files:
>main.py -> contains main() modules and uses a global variable (say a)
>incr.py -> contains incre() that changes the value of global variable a
>(called in main())
>
>Is there a way to reflect the change in main()?
>  
>

Hm, second time today that this question has been asked.  (And both 
posts sport an .edu address, too.)  Coincidence?

In answer to your question -- not with bare names, unless you're willing 
to do (at a minimum) some nasty black magic (hacking the stack frame and 
the like).  (And no, I don't know offhand how to do this black magic, 
nor would I wish to use it to allow such behavior.  Globals are almost 
always a bad idea.)

You can accomplish much the same ends in a much cleaner/clearer fashion 
by avoiding the 'from a import *' in favor of 'import a', and referring 
to the global variabler as an attribute of a: 'a.a = a.a + 100'.  (This 
is generally the preferred way of sharing variables across modules.) 

If you insist on import * to get bare names (which I would strongly 
recommend against), then you can still mutate shared objects and see the 
effects of that mutation in different modules.  For instance, you could 
bind the name a in a.py to an object that would allow itself to be 
incremented and decremented (using __iadd__(), etc), and which can be 
coaxed to resolve to that value when used in an expression.  This would 
allow you to modify the value by using 'a += 100', for example.  
However, the moment you rebind the name (as you do in your code, with 'a 
= a + 100'), you are creating a new variable that is local to the 
current scope, overriding the global a and potentially raising an 
UnboundLocalError.

So the short answer to your question is no, and you probably don't want 
to anyhow.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list