Closure
programming technique
Phillip J Eby at [z2004-12-05-PythonIsNotJava] If you find yourself writing the same function over and over again with minor variations, it's time to learn about closures. They're really not that scary. Here's what you do. You write a function that contains a function. The inner function is a template for the functions that you're writing over and over again, but with variables in it for all the things that vary from one case of the function to the next. The outer function takes parameters that have the same names as those variables, and returns the inner function. Then, every place where you'd otherwise be writing yet another function, simply call the outer function, and assign the return value to the name you want the "duplicated" function to appear. Now, if you need to change how the pattern works, you only have to change it in one place: the template.
Martin Fowler: http://www.martinfowler.com/bliki/Closure.html
- his Ruby examples translated into Python
note on Python variable-scope issues
as part of Functional Programming - http://www-128.ibm.com/developerworks/linux/library/l-prog2.html
Edited: | Tweet this! | Search Twitter for discussion