Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why doesn't python delete a function's variables when it it out of scope?

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading