Globals

Erik Max Francis max at alcyone.com
Wed Oct 16 18:32:04 EDT 2002


Newt wrote:

> Questions:
> 
> 1. Is this the correct/best way?
> 2. To save typing in all the global statements, can I put them in to
> an
> include file or a source file?

No, you can't.  The global statements are notes in local scopes that
some names should refer to the global names, not the local ones.  These
statements by definition have to be located in the _local_ scope, or
otherwise they wouldn't serve their purposes.

> 3. If I declare them in a .py file, do I still need the global
> commands to
> use them within Classes and Functions etc defined within that same
> module?

I find it's pretty rare that I have to use a true global variable --
that is, a variable at toplevel scope that actually gets rebound or
points to a mutable object.  (A "constant" is global in the sense of
being available everywhere but obviously won't be changing so the bag of
worms with modifying globals doesn't enter into it.)

In the cases where I do need a mutable or rebindable global, I simply
include the global statements wherever the globals are referenced
(whether they're accessed or rebound).  You only need the global
statements where there is an ambiguity to be resolved, but I find it
much more appropriate to simply use it wherever the globals are
referenced.  In practice, globals are rare enough, and the number of
local scopes where the globals are actually referenced is low enough to
make this not unreasonable.

Note that I don't bother to do this with "constants" -- i.e., globals
that are always only referenced, never modified or rebound.  In my (not
uncommon style) these are always represented with all-uppercase
identifiers so they stand out enough to not cause a problem.

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, USA / 37 20 N 121 53 W / &tSftDotIotE
/  \ Ride / Ride this wave of mine
\__/ Res
    Sade Deluxe / http://www.sadedeluxe.com/
 The ultimate Sade encyclopedia.



More information about the Python-list mailing list