Skip to content Skip to sidebar Skip to footer

Closure Magic In Higher-order Functions.

It's easy to know how to assign a global variable to an inner function - which would make the global variable a function itself thats equal to the inner function - but how does the

Solution 1:

I don't have enough reputation for a comment, so I have to write an answer...

From the excellent "Fluent Python" by Luciano Ramalho:

"...Python keeps the names of local and free variables in the __code__ attribute that represents the compiled body of the function"

"To summarize: a closure is a function that retains the bindings of the free variables that exist when the function is defined, so that they can be used later when the function is invoked and the defining scope is no longer available"

I added a couple of rows to your code to visualize this:

def outer(arg):
    def inner(arg2):
        print(arg, ',', arg2)
    print (inner.__code__.co_freevars)
    print (inner.__closure__[0].cell_contents)
    return inner

Which prints the following:

In [169]: outer('outer arg')
('arg',)
outer arg

So as you can see the value of arg is preserved even after the function has gone out of scope, since it is a free variable. The binding for arg is kept in the __closure__ attribute.

This is only a hint for further reading, I am by no means an expert.


Post a Comment for "Closure Magic In Higher-order Functions."