The global statement

Duncan Booth duncan at NOSPAMrcp.co.uk
Wed Jul 23 11:31:57 EDT 2003


"David Hitillambeau" <edavid at intnet.mu> wrote in 
news:pan.2003.07.23.15.14.52.430267 at intnet.mu:

> On Wed, 23 Jul 2003 16:56:08 +0200, Thomas Güttler wrote:
> 
>> If foo and bar are in the same file, 
>> you don't need the "global".
> 
> Then when is "global" required? What is it's role?
> 
I'm afraid Thomas Güttler's answer was a bit misleading.

You never need to use the 'global' statement outside a function. The only 
effect of 'global' is to declare that a variable assigned to within a 
function is actually a global variable. The fact that it is a global 
variable lasts only for the duration of the function in which it occurs.

Global variables are not in fact global. They are global only to the module 
in which they occur (usually you get one module per source file, although 
be aware that if you run a script A.py, it runs in the module __main__ and 
importing A will give you a second module from the same source, with its 
own global variables).

If you want to access a global variable from another module you don't need 
a global statement, just prefix the variable with a reference to the 
module. e.g. 'A.x' will access the global 'x' in module 'A'.

So:

 BAD=1

 def foo():
    global BAD
    BAD = 2

 def bar():
    BAD = 3
    global BAD

 def xyzzy():
    BAD="xyzzy"

 def plugh():
    print "BAD is",BAD

Outside the function assigning to BAD makes it a global variable. Inside 
foo and bar the global statement makes BAD a global variable for the 
assignment, notice that it doesn't matter where in the function the global 
statement occurs, although it is conventional to list globals at the head 
of the function.

'xyzzy' simply sets a local variable with the same name as the global.

'plugh' accesses the global: if you don't try to assign to it you don't 
need to tell Python its a global.

Finally, all of this confusion can be avoided if you use classes instead of 
global variables. e.g.

 class MyClass:
    def __init__(self):
       self.value = 0

    def foo(self):
       self.value = 1

    def bar(self):
       self.value = 2

 obj = MyClass()
 obj.foo()
 obj.bar()
 
-- 
Duncan Booth                                             duncan at rcp.co.uk
int month(char *p){return(124864/((p[0]+p[1]-p[2]&0x1f)+1)%12)["\5\x8\3"
"\6\7\xb\1\x9\xa\2\0\4"];} // Who said my code was obscure?




More information about the Python-list mailing list