UnboundLocalError Pitfall in Python

This is one of my earliest pitfall when learning Python and I would like to share it to other novices. Consider the following short program:

testCount = 0  # a global variable

def runTest():
    testCount = testCount + 1
    # more code here

# main body, run the test twice
runTest()
runTest()

Running this program will result in the following error:

UnboundLocalError: local variable ‘testCount’ referenced before assignment

To make long story short, despite the global declaration, Python still treated testCount as a local variable inside the function runTest(). To fix this situation, I used the global statement to declare testCount as a global variable like this:

testCount = 0  # a global variable

def runTest():
    global testCount # declare testCount a global variable
    testCount = testCount + 1
    # more code here

# main body, run the test twice
runTest()
runTest()

Now the program will execute the way I intended. A note regarding global variables: use them when you absolutely need to. Before resorting to global variables, try to explore other alternatives. If you have questions or comments, feel free to post on my blog. Thank you.

Blogged with Flock

Tags: , , ,

One thought on “UnboundLocalError Pitfall in Python

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s