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?
Decorators are an example of closures. For example,
The function
wrapped_functionis 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:
Also, bound methods are technically closures (though they’re probably implemented differently). Bound methods are class member functions with their class baked in:
wis essentially a closure with a reference to thesys.stdoutobject.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.