evan54
evan54

Reputation: 3733

Why is the variable still available after the function is executed?

I'm trying to understand scope here a bit better.

def f1():
    a = 1
    def g1(X):
        return X+a
    return g1

def f2():
    a = 1
    def g2(X):
        return X+1
    return g2

g1 = f1()
print g1(4)
g2 = f2()
print g2(4)
# both give 5 as you'd expect

My problem is that isn't a destroyed? In which scope is it available? My general understanding was that in the second case of f2 a is definitely not available once the function returns. This way for example if you have giant arrays or variables in terms of memory once the function returns they're no more.

What happens here?

EDIT:

Is b ever available here?

def f1():
    a = 1
    b = 1
    def g1(X):
        return X+a
    return g1

Upvotes: 1

Views: 72

Answers (1)

BrenBarn
BrenBarn

Reputation: 251408

If a function contains another function, and the inner function contains references to variables in the outer function, and the inner function is still "alive" after the outer function ends (i.e., it is returned or a reference is somehow created to it), a closure is created, which "saves" those variables, making them available to the inner function when it is called.

In your second example, b is not available, because the inner function g1 does not reference it, so it is not saved in the closure.

Upvotes: 5

Related Questions