I "think" global is broken

sismex01 at hebmex.com sismex01 at hebmex.com
Wed Nov 6 17:10:34 EST 2002


> From: Larry Bates [mailto:lbates at swamisoft.com]
> 
> The following code works as expected.
> 
> class test:
>     global _trace
>     def __init__(self):
>         if _trace: print "entering test.__init__"
>         return
> 
> global _trace
> _trace=1
> x=test()
> 
> 
> Now if I move the class into a separate module called test.py
> and change the main program it no longer works
> 
> from test import *
> global _trace, _debug
> _trace=1
> x=test()
> 
> I get undefined global error
> 
> I just don't believe that this is the way it should work.
> I understand that in this simple example I could
> do an import test and (according to other posts
> I've read it should work).  But in a real world
> example the external module has 8 classes in it
> (and growing).  It just doesn't seem right that I
> would need to split it into 8 different modules.
> 
> Am I missing something?
> Thanks in advance for any assistance.
> 
> Regards,
> Larry Bates
> lbates at swamisoft.com
> 

As explained in another thread a bit ago, "globals" aren't
truly "global", in the traditional sense of the word. Or,
in the "customary" sense of the word.

A global variable in Python is one that exists at the
module level, and not as a local variable in a function
or as an instance or class variable.

Also, it only makes sense to do "global <varname>"
inside a function, so that when you assign to <varname>
it doesn't live as a local variable inside the function,
but rather as a module-level variable.

The only truly global _IDENTIFIERS_ are those inside __builtins__,
but that is an implementation detail (as explained by f/bot) and,
although you could create a truly global shared variable by
assigning it to __builtins__.<varname>, nothing stops the Python
team from changing that behaviour eventually.

So, retaking your example, in the second instance where it fails,
when you execute "from test import *", you bring into __main__
(assuming your in the python shell) all identifiers in test
which don't start with an underscore. BUT, wait a second; all
functions which you import "remember" which module they come
from, so when you execute "global" inside an imported function,
it's accessing the module's namespace, and not the "importing"
namespace.

So, when you run "x=test()" the second time, the class tries
to access a global variable (actually, a module variable)
called "test._trace", and not "__main__._trace", which is
your intent.

HTH

It's kinda tricky, ain't it. :-)

-gustavo




More information about the Python-list mailing list