Why can't I set a global variable in Python?

slim picture slim · Aug 15, 2009 · Viewed 50.9k times · Source

How do global variables work in Python? I know global variables are evil, I'm just experimenting.

This does not work in python:

G = None

def foo():
    if G is None:
        G = 1

foo()

I get an error:

UnboundLocalError: local variable 'G' referenced before assignment

What am I doing wrong?

Answer

Greg Hewgill picture Greg Hewgill · Aug 15, 2009

You need the global statement:

def foo():
    global G
    if G is None:
        G = 1

In Python, variables that you assign to become local variables by default. You need to use global to declare them as global variables. On the other hand, variables that you refer to but do not assign to do not automatically become local variables. These variables refer to the closest variable in an enclosing scope.

Python 3.x introduces the nonlocal statement which is analogous to global, but binds the variable to its nearest enclosing scope. For example:

def foo():
    x = 5
    def bar():
        nonlocal x
        x = x * 2
    bar()
    return x

This function returns 10 when called.