When I execute
x = 0
def f():
print('x' in locals())
x = 1
print('x' in locals())
f()
I get what I expect, namely
False
True
Yet when I execute
x = 3
def f():
print(x, 'x' in locals())
x = 7
print(x, 'x' in locals())
f()
I expect to get
3 False
7 True
but instead I get the UnboundLocalError
.
If Python knows that on the next line there comes an assignment of the label x
in the local scope (and so the name x
is already in the local scope but it wasn't assigned yet) then why does it let me inquire about x
in my first code?
Added:
Why does it raise the error even though x = 7
comes after the first print(x, 'x' in locals())
?