1

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
evan54
  • 3,585
  • 5
  • 34
  • 61
  • You may want to check out this [answer](http://stackoverflow.com/a/4020443/2297365). Your question is the essence of a closure in python. – huu Nov 25 '14 at 20:21

1 Answers1

5

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.

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • so in the new example `b` is not saved but `a` is, correct? – evan54 Nov 25 '14 at 20:22
  • You can actually see which variables are kept alive: `print g1.__closure__` to see that there's one "closure cell", then `print g1.__code__.co_freevars` to see the names of all closure cells, and `print f1.__code__.co_cellvars` to see things from the outer function's point of view. – abarnert Nov 25 '14 at 21:14