[Tutor] global statement?

dman dsh8290@rit.edu
Wed, 15 Aug 2001 11:23:06 -0400


On Wed, Aug 15, 2001 at 09:23:17AM -0500, Rob Andrews wrote:
 
| *Learning Python* (pp. 99-105) points out that declaring globals from
| within functions is possible, and shows how. I'm trying to think of
| *why* one might want to declare or modify a global from within a
| function.
| 
| A friend who knows quite a bit more than I do about the subject said
| "That's the first thing about python I've seen that really makes me go
| "yecchhh.".  Global variables have to be declared outside the scope of
| any functions or methods in almost every langauge except Perl."

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.

Usually global variables will be created in their global context (ie
at module level), but sometimes may need to be changed.  I think that
configuration options are a good example of this -- some module should
have all the global configuration options and initially they will have
a default value.  Then a function (or more) may parse some config file
and modify those global variable to contain their new values.
Admittedly 'global' has limited usefulness in a well-designed program
but it does have its place.

HTH,
-D