Python Forum
How does UnboundLocalError work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How does UnboundLocalError work?
#1
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?
Reply
#2
you're missing the colon on function definition (I do it once in a while, then sit scratching my head)
Reply
#3
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?
Reply
#4
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  UnboundLocalError: local variable 'wmi' referenced before assignment ilknurg 2 1,907 Feb-10-2022, 07:36 PM
Last Post: deanhystad
  exec + subprocess = UnboundLocalError paul18fr 6 3,494 Feb-04-2021, 06:27 AM
Last Post: Gribouillis
  UnboundLocalError: local variable 'figure_perso' referenced before assignment mederic39 2 2,267 Jun-11-2020, 12:45 PM
Last Post: Yoriz
  UnBoundLocalError Seaninho 3 2,672 May-31-2020, 07:22 AM
Last Post: azajali43
  UnboundLocalError: local variable referenced before assignment svr 1 3,298 Dec-27-2019, 09:08 AM
Last Post: perfringo
  UnboundLocalError: local variable ' ' referenced before assignment d3fi 10 5,532 Sep-03-2019, 07:22 PM
Last Post: buran
  'Exception Has occured: UnBoundLocalError' caston 1 2,447 Jun-12-2019, 02:33 PM
Last Post: perfringo
  UnboundLocalError Problem DrChicken24 1 2,225 Mar-27-2019, 02:53 AM
Last Post: ichabod801
  UnboundLocalError, how to fix it please? etrius 4 3,871 Jan-18-2018, 09:53 PM
Last Post: nilamo
  How to fix UnboundLocalError Tawnwen 5 5,337 Jan-07-2018, 05:38 PM
Last Post: Gribouillis

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020