Unbound Variables in Python
How Python figures out the scope of it's variables?
Consider the following example
def take_sum(a, b, c):
<function take_sum at 0x1031c84c0>
Python looks for
take_sumin local scope ie., inside main followed by global scope whereas,
if "take_sum" not in globals():
take_sum = lambda x,y,z: x+y+z
UnboundLocalError: local variable 'take_sum' referenced before assignment
The function raises an exception because the compiler saw that the code could assign to
take_sumas a local variable, and so it makes all the references to
take_sumin the code be local. You can no longer look up the global variable
take_sumin the normal way once that determination has been made.
Last modified 5mo ago