global variable not seen (bug?)

andy andy at eastonwest.co.uk
Wed Jan 8 15:19:20 EST 2003


Global variables in Python had me going for a while, too.  My Pascalesque 
background taught me (what I call) *implied* *nested* *scoping*.  

Considering the following program fragment:

var x:integer (* a global variable *)

function referencex(z:integer):integer;

var y: integer; (* a local variable *)

begin
	y:=x*z;	(* assign local var y product of x and y *)
	if x>z then  (* reference the value of x *)
		a:=z   (* return z as result *)
	else 
		a:=x;  (* return x as result *)
end;


procedure assignx(z:integer); 

begin
	if z<x then
		x:=z; (* assign global var x value of z *)
end;
	
procedure localx(z:integer);

var x:integer;

begin
	x:=z*2;  (* assign to local var x *)
end;

### Yes, none of that does anything sensible, I know :-P

In function referencex(),  global variable x is referenced, but not modified; 
this function has no /side/ /effects/.

In procedure assignx(), global variable x is assigned to, changing its value;

In procedure localx(), the global variable x remains untouched, as there is 
another, local variable of the same name, which gets assigned to.


My point here, is that my experience had lead me to expect this kind of 
behaviour; Pascal, Modula, Oberon, C, C++ etc. all follow roughly the same 
rules.

Python (being Python, of course) does it differently!

In Python, (correct me if I'm wrong) you declare it the other way round, that 
is, a variable in the global scope is not assignable unless you say so, using 
the global statement.  If you declare a variable as global in a procedure, 
you cannot also have a local variable with the same name.

To me, the advantage is that you are *declaring* that a procedure has a 
*side-effect* - the global statement is a flag that the procedure alters 
variables outside its own scope.  That's a Good Thing.

# Global variable example

x=1 # declare global x and assign value

def referencex(z):
    y=x*z # assign local var y product of x and y 
    if x>z: # reference the value of x
        return z   #return z as result 
    else:
        return x  # return x as result 

def assignx(z):

    global x  # this procedure needs to modify x

    if z<x:
        x=z # assign global var x value of 
	
def localx(z):
    x=z*2 # assign to local var x 
    # can't reference global x below here (in this procedure)
    






More information about the Python-list mailing list