Namespace confusion

Christopher A. Craig com-nospam at ccraig.org
Fri May 11 09:24:14 EDT 2001


Daniel Klein <danielk at aracnet.com> writes:

> When I check globals() at the interactive prompt, my instances are indeedy
> there. What's going on here?

You checked globals() for the current namespace.  Try printing
globals() in the module namespace and I think you will find your
answer.

The following code further illustrates the difference:

testmod.py:
globala = 6

def testfunc(a):
  global globala
  globala += a  
  return globala



Example 1:
>>> import testmod
>>> globala = 4
>>> testmod.testfunc(3)
7
>>> globala
4
>>> testmod.globala
7
>>>

Example 2:
>>> from testmod import testfunc
>>> globala = 3
>>> testfunc(3)
7
>>> globala
3
>>>


Each module has its own global namespace and when a module's
function is executed (even if it is imported into a different
namespace) it uses its parent modules global namespace.

This ends up being extremely useful.  I have almost overcome my
clinical aversion to global variables because of the utility of
module-globals for state and caching and the fact that I am assured my
globals won't infect namespaces outside the module (esp. if they are
named starting with an underscore)



-- 
Christopher A. Craig <com-nospam at ccraig.org>
So do not worry about tomorrow, for tomorrow will care for itself.  Each day
has enough trouble of its own.  -- Matt 6:34 (NASB)



More information about the Python-list mailing list