I "think" global is broken

Fredrik Lundh fredrik at pythonware.com
Wed Nov 6 17:08:53 EST 2002


Larry Bates wrote:

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

"global" is a compiler directive that tells Python that a variable inside
a function or method is not local to the function, but belongs to the
module that function/method is defined inside.

you can learn more about local and global namespaces here:

    http://www.python.org/doc/current/ref/naming.html


if you want to create "global variables", put them in a module that
you import into your own modules.

#
# mymodule.py

import common

class test:
    def __init__(self):
        if common.trace: print "entering test.__init__"
        return

#
# common.py

trace = 0

#
# main.py

import mymodule
import common

common.trace=1

x=mymodule.test()

</F>





More information about the Python-list mailing list