Guilty secret: globals baffle me

Alex Martelli aleax at aleax.it
Wed Nov 6 09:53:56 EST 2002


Edward K. Ream wrote:
   ...
> 1. How many globals are there?  Is there just one, or does each module
> define its own?

The latter.  Each module has its own globals-dictionary.


> 2. It seems that:
> 
> global foo
> foo = x
> ...
> global
> print foo
> 
> only works if the two parts are within the same module, so I think maybe
> globals() returns module specific stuff, but then why call it globals?

It seems that you haven't noticed the existence of functions (and
their namespaces, particularly their crucial local namespace).

The global statement only makes sense inside a function: it tells the
Python compiler that certain names, that the function binds, rebinds
or unbinds, are NOT (as is the normal case) local to the function, but
rather refer to names in the module's globals-dictionary.

Outside of any function, all names refer to the module's globals-
dictionary, therefore the global statement is redundant -- useless,
although technically innocuous.

Given that names that only exist within a function are commonly
called "local names" or "local variables" of that function, how
else would you call names that AREN'T local, but rather global
to all functions within the module?  Calling them "module names"
would IMHO be far more confusing than calling them "global
names" -- I think of module names as the names of modules; and
the local/global distinction would become quite confused.


Alex




More information about the Python-list mailing list