1

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?

1 Answers1

-2

Local symbol table stores all information related to the local scope of the program, and is accessed in Python using locals() method. however more details can be accessed from scope

mkrana
  • 422
  • 4
  • 10
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/low-quality-posts/22910382) – Pino May 02 '19 at 18:06
  • @Pino Thanks for guidance. – mkrana May 02 '19 at 18:07
  • I followed your link but didn't find any answer to my question. I think I don't have trouble understanding scopes.My question just was: Why is x already member of local namespace at the time of invoking locals(), even though the line "nonlocal x" where the reference is set, comes afterwards? – user2874667 May 02 '19 at 18:13
  • @user2874667, you are correct actually i misunderstood your question. however this looks to be a duplicate to [link](https://stackoverflow.com/questions/1261875/python-nonlocal-statement) – mkrana May 02 '19 at 19:02
  • This is still not an answer. Eventually, my question has little to do with keyword nonlocal. Leaving it out results in the same output. I only wonder that I don't have to swap the lines within function g to get this result. – user2874667 May 03 '19 at 04:12