Python Forum
How does UnboundLocalError work? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How does UnboundLocalError work? (/thread-36487.html)



How does UnboundLocalError work? - deanhystad - Feb-24-2022

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?


RE: How does UnboundLocalError work? - Larz60+ - Feb-25-2022

you're missing the colon on function definition (I do it once in a while, then sit scratching my head)


RE: How does UnboundLocalError work? - deanhystad - Feb-25-2022

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?


RE: How does UnboundLocalError work? - bowlofred - Feb-25-2022

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.