global variable not seen (bug?)
andy at eastonwest.co.uk
Wed Jan 8 21:19:20 CET 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 *)
var y: integer; (* a local variable *)
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 *)
a:=x; (* return x as result *)
if z<x then
x:=z; (* assign global var x value of z *)
x:=z*2; (* assign to local var x *)
### 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
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
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
return x # return x as result
global x # this procedure needs to modify x
x=z # assign global var x value of
x=z*2 # assign to local var x
# can't reference global x below here (in this procedure)
More information about the Python-list