To serve as closure function, it is important for an inner functions to have access to variables defined in surrounding scopes. But why does locals() function tell us that these variables are member of local namespace, even if they are referenced to after invokation of locals()?
I referenced to a nonlocal variable x after invocation of locals(), even after return statement. I even preceded it with keyword nonlocal. But nothing changed.
def f():
x=0
def g():
print(locals())
return
nonlocal x
g() # prints "{'x': 0}"
x=1
g() # prints "{'x': 1}
return g
g=f()
g() # prints "{'x': 1}
Since x is referenced after (and not before) invocation of locals(), I would expect that an empty dictionary {} is printed. But instead, the result is first {'x': 0}, and after changing within outer scope {'x': 1}. Actually, it isn't even a local variable, since it can be modified from surrounding scope. What is actually going on?