2

Let's suppose to have this simple code:

def my_outer_function():
    outer_var = 123
    def my_inner_function():
        return outer_var + 1
    return my_inner_function

get_inner = my_outer_function()
get_inner()                      

I wonder there isn't any kind of runtime error. outer_var - the variable of the outer function - is available only when that function is running on, i.e. it vanishes when my_outer_function ends. But when I call get_inner(), my_outer_function() is already ended so I would have bet on a runtime error since my_inner_function couldn't find outer_var.

How do you explain all this?

Paul Rooney
  • 19,499
  • 9
  • 39
  • 60
enneppi
  • 969
  • 2
  • 13
  • 31
  • 4
    Its called a [closure](http://stackoverflow.com/questions/13857/can-you-explain-closures-as-they-relate-to-python). – Paul Rooney Jan 04 '17 at 22:44
  • 1
    This is called a "closure". When you return the inner function, it captures the binding of the outer variable. – Barmar Jan 04 '17 at 22:44

1 Answers1

2

the variable of the outer function is available only when that function is running on, i.e. it vanishes when my_outer_function ends.

That's not entirely true. The variable is available in my_outer_function's scope. my_inner_function has the scope of its own declarations and its parent's scope.

my_inner_function references a variable outside of its own scope, and so those references are bound to my_inner_function as a closure when its parent's scope is no longer available. To learn more about closures, see Can you explain closures (as they relate to Python)? (taken from Paul Rooney's comment)

Graham
  • 7,035
  • 17
  • 57
  • 82
Rushy Panchal
  • 15,807
  • 15
  • 56
  • 90