global and None

Leo Yee surffirst at yahoo.com
Tue Dec 23 02:17:05 EST 2003


Hi,

I was confused by the global statement and None.
Consider the following code:

--- code begin ---

global g
g=None
def foo():
    if g==None:
        g=0
foo()

--- code end ---

My purpose is to init g. This is very useful when we cannot construct a
global variable.
But what I got was:
UnboundLocalError: local variable 'g' referenced before assignment

So I try to solve the problem in this way:
--- code begin ---

global g
g=None
def foo():
    global g
    if g==None:
        g=0
foo()

--- code end ---

And it works but the python documentation told me the following:
"Names listed in a global statement must not be defined as formal parameters
or in a for loop control target, class definition, function definition, or
import statement. "

Does anyone know what I should do to solve this problem? Thanks in advance.

Leo Yee








More information about the Python-list mailing list