2

I was wondering about the scope of the variable a in the following Python snippet,

# ============================
def get_plotter():
    def get_a():
        return a
    a = 3.14
    return get_a
# ============================
if __name__ == '__main__':
    f = get_plotter()
    print f()
# ============================

The output is 3.14, but looking at the code I would have expected a to go out of scope as soon as get_plotter() terminates, effectively leaving an undefined something.

Is it just volatile memory contents that are printed here? What's going on?

Nico Schlömer
  • 53,797
  • 27
  • 201
  • 249

1 Answers1

4

This works because of closures, or "functions with data attached", and is explained well here

https://stackoverflow.com/a/141426/735204

Community
  • 1
  • 1
Emmett Butler
  • 5,969
  • 2
  • 29
  • 47