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

Question:

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?

Asked By: slim

||

Answers:

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.

Answered By: Greg Hewgill

You still have to declare G as global, from within that function:

G = None

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

foo()
print G

which simply outputs

1
Answered By: Mark Rushakoff

Define G as global in the function like this:

#!/usr/bin/python

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

foo();

The above python prints 1.

Using global variables like this is bad practice because: http://c2.com/cgi/wiki?GlobalVariablesAreBad

Answered By: Nope

You need to declare G as global, but as for why: whenever you refer to a variable inside a function, if you set the variable anywhere in that function, Python assumes that it’s a local variable. So if a local variable by that name doesn’t exist at that point in the code, you’ll get the UnboundLocalError. If you actually meant to refer to a global variable, as in your question, you need the global keyword to tell Python that’s what you meant.

If you don’t assign to the variable anywhere in the function, but only access its value, Python will use the global variable by that name if one exists. So you could do:

G = None

def foo():
    if G is None:
        print G

foo()

This code prints None and does not throw the UnboundLocalError.

Answered By: David Z
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.