In python, I know that functions run in the context that they are called from, not the context that they are defined in. However, in the code below, where a function is returned from another function, it still has access to the variables (specifically the list ‘cache’) of the function it was defined in, even though that function is now out of scope (I think), and so I would have though it’s variables would have been deleted. But it can also access global variables from the current context?
def wrapper(func):
cache = []
def func_new(n):
cache.append(func(n))
print(cache)
return func_new
def add1(n):
return(n+1)
x = wrapper(add1)
x(5)
x(2)
print(cache)
>Solution :
It doesn’t?
>>> x = wrapper(add1)
>>> x(5)
[6]
>>> x(2)
[6, 3]
>>> print(cache)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
print(cache)
NameError: name 'cache' is not defined
As for the cache variable being defined within the wrapper, that matches behavior elsewhere; the function has access to all variables where it is defined. The opposite is not true; variables defined in the function are not accessible in the context scope unless explicitly a global.
Does this example help?
>>> x = 4
>>> def test():
print(x)
>>> test()
4