[Tutor] global statement?

alan.gauld@bt.com alan.gauld@bt.com
Wed, 15 Aug 2001 17:51:46 +0100


> | "yecchhh.".  Global variables have to be declared outside 
> | any functions or methods in almost every langauge except Perl."

That was my initial reaction too. I was surprised global had 
the side effect of allowing creation of global variables from 
inside a function. But when you stop and think about how Pythons 
namespace mechanism works it makes sense. I still don't like 
it as a mettter of style.

> The only reason the 'global' statement exists is to allow _assignment_
> to a global name.  If the global statement is left out then the
> assignment will create a new _local_ binding that overshadows the
> global one.  Reading a global variable requires no special syntax.

Yes and thats what I thought global did - allowed assignment to 
an already existing variable declared external to the function.
In fact it tells python that any references to the variable are 
interpreted in the context of the global namespace thus assignment 
will create a new variable.

So:

#### seta.py ####
def setA(n):
  global a
  a = n

#################

### main.py #####
import seta

# print seta.a    # a name error, no a exists yet

for j in range(10):
   seta.setA(j)

print seta.a	# now exists and set to 9

seta.a = "Now a string!"
print seta.a	# now set to the string

#################

creates a new variable 'a' in the seta namespace.
Sets it to the values from 0-9

The ability to create a new variable in seta via a call to 
a function could be used as a powerful form of data 
abstraction I guess. Almost a kind of data hiding - except 
its not really hidden!

> Usually global variables will be created in their global context (ie
> at module level), but sometimes may need to be changed.  

Yes that's fine

> Admittedly 'global' has limited usefulness in a well-designed program
> but it does have its place.

No issue about global its the 'side-effect' of creating a new variable
inside the call to the function. Effectively this makes the module 
stateful - definitely a mixed blessing. A bug or a feature? hmmm.

Alan g.