How do local variables work with Python closures?
问题 When I run the following Python3 code, def f(): x = 'foo' def g(): return x def h(y): nonlocal x x = y return g, h g, h = f() print(g()) h('bar') print(g()) I get foo bar I had believed that in Python, all local variables are essentially pointers. So in my mind, x was a pointer allocated on the stack when f() is called, so when f() exits, the variable x should die. Since the string 'foo' was allocated on the heap, when g() is called, I thought "ok, I guess g() kept a copy of the pointer to