Python/Closures
< Python
Why are useful
A closure is a way to define a variable statically into a function. They are good to:
- Replace hard coded constants;
- Eliminate globals.
Some examples
Define a function that return another function:
def print_something(msg):
def _print(var):
print msg % var
return _print
Now we can use to instantiate the function and define the string formatting statically and then call the returned function.
>>> p = print_something('Hi %s!')
>>> p('Pietro')
Hi Pietro!
Now a more interesting example for the grass users:
from grass.pygrass.modules import Module
def get_module(cmd):
mod = Module(cmd)
def do(**kwargs):
mod(**kwargs)
return do
If we test the speed of a GRASS module, using ipython I got:
>>> %timeit Module('g.region', flags='p')
10 loops, best of 3: 30.8 ms per loop
Instead, using the python closure, I got:
>>> greg = get_module('g.region')
>>> %timeit greg(flags='p')
100 loops, best of 3: 12.8 ms per loop
Note: This example doesn't work with multiprocessing.