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 'foo'
as well". But then I could call h('bar')
, the value that g()
returns got updated.
Where does the variable x
live? Is my model of local variables in Python all wrong?
EDIT:
@chepner has pretty much answered my question in the comments. There's one where he says that local variables are stored in a dict-like object, and then another where he links https://docs.python.org/3.4/reference/executionmodel.html#naming-and-binding, to support his claim.
At this point I am pretty happy. If chepner were to write an answer rehashing his comments I would accept it as best answer. Otherwise, consider this question resolved.