Home > Blockchain >  Do variables in closures have their own scope?
Do variables in closures have their own scope?

Time:07-25

I have two questions about this code:

def a_funcs():
    class A:
        def __init__(self):
            self.a = 0

    a_local = A()
    def set_a(a):
        a_local.a = a
    def get_a():
        return a_local.a
    return set_a, get_a

set_a, get_a = a_funcs()
print(get_a())
set_a(17)
print(get_a())

Does a_local keep existing after a_funcs have been returned? Is it still in the scope of a_funcs? Can it happen that the garbage collector deletes a_local?

Where is a_local stored technically? On the stack or on the heap?

CodePudding user response:

The name a_local is scoped in a_func. The variable is no longer aaccessible by this name after returning from the function. When you enter the function again, you will get a new one.

But the (mutable) value where it points to cannot be deleted by the garbage collector. There are still references to it, hidden in the function set_a and set_b. These functions are still accessible after returning from the function a_func.

The pointer to the piece of storage where the value of a_local is located is on the stack. But the storage for the value must be on heap because it keeps living after returning from a_func.

CodePudding user response:

Not disagreeeing with @donat, but expanding upon what he wrote. Try:

set_a1, get_a1 = a_funcs()
set_a2, get_a2 = a_funcs()

set_a1(10)
set_a2(20)
print(get_a1())
print(get_a2())

You will see that each call to a_funcs() creates a new variable, and that the functions returned by a_funcs() refer to the variable that was just created.

  • Related