Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Closure function
#1
Closure function doesn't make sense:
def make_multiplier_of(n):
    def multiplier(x):
         return x * n
    return multiplier
times3 = make_multiplier_of(3) 
times5 = make_multiplier_of(5)
Can anybody explain the implementation detail how python can know a function is a closure function and don't delete the enclosing function's name and their value after the enclosing function return ? And where that value is stored ? I didn't even call the multiplier function in the make_multiplier_of function, so how python can go to the body code and know that is a closure function and retain the required information ?
Reply
#2
A function definition creates both a variable name and a value in the current namespace
>>> def multiplier(x):
...     return x * n
... 
>>> multiplier
<function multiplier at 0x7f2ace916e18>
You see that the function definition creates the variable named 'multiplier' and this variable has a value which is a 'function object'.

In your code, the return multiplier returns this function object to the calling environment and this returned value is caught by the variable times3 in the assignment statement times3 = make_multiplier_of(3). This is how python remembers the function.

The function object contains a compiled version of the body code (a 'code object') and this is how python is able to execute the function later.

The function object can be passed around like any other python object. For example you could write
foobarbaz722 = times3
print(foobarbaz722(10))
Reply
#3
But, how can python know a function is a closure function and retain the required information ?. I didn't call the multiplier in make_multiplier_of so python doesn't know that i'll use an enclosing scope's variable (because python runs the body code only when the function is called). So how can python still retain the value of n and didn't delete the name and the value (in this case because i don't have other reference to that value) as it usually does
Reply
#4
The function objects keeps a reference to the value, although it's somewhat nested in the structure
>>> times3.__closure__[0].cell_contents
3
>>> times5.__closure__[0].cell_contents
5
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020