Namespace confusion

Daniel Klein danielk at aracnet.com
Sat May 12 02:54:45 EDT 2001


Thanks Christopher, that helps a lot.

Dan

On 11 May 2001 09:24:14 -0400, com-nospam at ccraig.org (Christopher A. Craig)
wrote:

>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)




More information about the Python-list mailing list