Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better illustration of Closures?

I am learning Python using Dive Into Python 3 book. I like it, but I don't understand the example used to introduce Closures in Section 6.5.

I mean, I see how it works, and I think it's really cool. But I don't see any real benefit: it seems to me the same result could be achieved by simply reading in the rules file line by line in a loop, and doing search / replace for each line read.

Could someone help me to:

  • either understand why using closures in this example improves the code (e.g., easier to maintain, extend, reuse, or debug?)

  • or suggest a source of some other real-life code examples where closures really shine?

like image 316
max Avatar asked May 09 '10 06:05

max


People also ask

What are closures explain with an example?

It creates functions that can add a specific value to their argument. In the above example, the function factory creates two new functions—one that adds five to its argument, and one that adds 10. add5 and add10 are both closures. They share the same function body definition, but store different lexical environments.

What are closures few common uses for closures?

Closures are frequently used in JavaScript for object data privacy, in event handlers and callback functions, and in partial applications, currying, and other functional programming patterns.


1 Answers

Decorators are an example of closures. For example,

def decorate(f):
    def wrapped_function():
        print("Function is being called")
        f()
        print("Function call is finished")
    return wrapped_function

@decorate
def my_function():
    print("Hello world")

my_function()

The function wrapped_function is a closure, because it retains access to the variables in its scope--in particular, the parameter f, the original function. Closures are what allow you to access it.

Closures also allow you to retain state across calls of a function, without having to resort to a class:

def make_counter():
    next_value = 0
    def return_next_value():
        nonlocal next_value
        val = next_value
        next_value += 1
        return val
    return return_next_value

my_first_counter = make_counter()
my_second_counter = make_counter()
print(my_first_counter())
print(my_second_counter())
print(my_first_counter())
print(my_second_counter())
print(my_first_counter())
print(my_second_counter())

Also, bound methods are technically closures (though they're probably implemented differently). Bound methods are class member functions with their class baked in:

import sys
w = sys.stdout.write
w("Hello\n")

w is essentially a closure with a reference to the sys.stdout object.

Finally, I haven't read that book, but a quick read of the chapter you linked and I'm very unimpressed--it's so horribly roundabout that it's useless as an explanation of closures.

like image 166
Glenn Maynard Avatar answered Sep 25 '22 13:09

Glenn Maynard