1

I came across an example of a factory function similar to this

def my_factory(a):
    def my_factory_function(b):
        return b ** a
    return my_factory_function

Given this code the function, my_factory_function may be accessed in this manner...

>>> f =  my_factory(2)
>>> print f 
<function my_factory.<locals>.action at 0xwhatever>

Now I'm completely onboard here but am confused by what happens next...

>>> f(3)
9 

So in this step it manages to square the value 3 or evaluate the code return 3 ** 2

Finally, what Im wondering about is how the nested function managed to retain state information about the value of a. This was initially defined when I called f = my_factory(2) but I'd imagine the value would've gone out of scope by the point I'm calling the nested function. Does this mean that any instance in which a function is stored as a variable that functions state information is stored along with it?

Raphi
  • 410
  • 4
  • 17
  • This function could probably be improved with a lambda expression but thought it appeared clearer what was happening like this. – Raphi Sep 09 '14 at 18:14
  • 5
    This is called a [**closure**](http://en.wikipedia.org/wiki/Closure_%28computer_programming%29). I voted to close your question as a duplicate not because it's a bad question (quite the opposite), but because the answers to the linked question should pretty much answer your question as well. – Lukas Graf Sep 09 '14 at 18:15
  • 1
    And yes, it behaves exactly like you describe it in your last paragraph: The inner function's enclosing environment gets "packaged" together with the function. – Lukas Graf Sep 09 '14 at 18:23

0 Answers0