Python Forum

Full Version: How does UnboundLocalError work?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
While answering a question on the forum I wrote an example where I knew the outcome, but I don't understand the reason for the outcome.
check = 0

def sample_fcn()
    print(check)
    check = 1
This generates an UnboundLocalError when doing the "print(check)". My question is "How does Python know there is a local variable named "check"?

I know that Python parses the function to generate bytecodes and this must include creating symbols for variables that the function will use. Is Python using this "symbol table" when looking for variables instead of the locals dictionary? Is there a way for me to see these symbols? Is there something I could read that describes how UnboundLocalError works?
you're missing the colon on function definition (I do it once in a while, then sit scratching my head)
Add the colon and it generates an UnboundLocalError instead of being a syntax error. The UnboundLocalError is what I'm curious about.

This is complete code to generate the exception.
check = 0
 
def sample_fcn():
    print(check)
    check = 1

sample_fcn()
How does Python know in line 4 that check is a local variable?
When it compiled the bytecode for the function, it saw that check gets an assignment. So without a global or similar, all references to check are made to the local variable.

When the runtime execution gets to line 4, the local variable doesn't exist yet, so it throws an exception.