The global statement

Andy Jewell andy at wild-flower.co.uk
Wed Jul 23 18:22:19 EDT 2003


Gentlepeople,

I found it easier to envisage the Python global statement as the inverse of 
the Pascal/Modula/C  concept:

In traditional (compiled procedural) languages, one *declares* a variable at 
the 'top-level' scope, and then uses it as one would a local variable in 
functions/procedures, but without declaring it again.  Global variables in 
these types of languages are treated differently in most respects (where they 
are stored for example: heap rather than stack, usually).  There is usually 
no special notation, however, to enable the reader (especially one not 
skilled in the language at hand) to determine that a given variable is, in 
fact, global or local: you have to know the scoping rules of the language.  
If you define a variable outside of a function, it's global (notwithstanding 
the placement/sequencing rules for that language).

Python is different (as always).  It allows you to *read* the value (pardon 
the over-simplification) of variables declared at the 'top level', that is, 
created outside of a function, but you can't *write* to it without first 
telling Python that you wish to do so (by using the global statement): 
forgetting to do so results in the creation of a similarly named local 
variable, with no relation whatsoever to the intended global variable. I tend 
to think of it as 'telling python it's ok to change' the variable.


pascal;

var a_global: integer;

function read_a_global;
begin
    read_a_global:=a_global; (* return the value of global variable *)
end;

procedure modify_a_global;
begin
    a_global:=10;  (* modify global variable *)
end;

end.


#python:
a_global=1

def read_a_global():
    return a_global # REFERENCE the global variable

def cant_modify_a_global():
    a_global = 10 # makes a local variable called a_global
    # which disappears after this point:

def modify_a_global(n):
    global a_global # Makes a_global locally accessible for modifying
    a_global = 10 # top-level a_global variable is modified



When I first tried to do this sort of thing in python, i wrote:

global a_global

def modify_a_global():
    a_global=10

...and wondered why it didn't work.  I admit that the docs didn't really help 
much either, as they don't tell you to put the statement *inside* the 
function that needs to modify the variable!  I only finally understood by 
reading some of the standard library code, after searching it for the word 
'global' itself!

just my 2p...

hope that helps

-andyj





More information about the Python-list mailing list