Python/Closures: Difference between revisions
< Python
(Add a new page) |
m (+category) |
||
Line 1: | Line 1: | ||
{{Python}} | |||
=Why are useful= | =Why Closures are useful= | ||
A closure is a way to define a variable statically into a function. They are good to: | A closure is a way to define a variable statically into a function. They are good to: | ||
* Replace hard coded constants; | * Replace hard coded constants; | ||
Line 28: | Line 28: | ||
<source lang="python"> | <source lang="python"> | ||
from grass.pygrass.modules import Module | from grass.pygrass.modules import Module | ||
def get_module(cmd): | def get_module(cmd): | ||
Line 54: | Line 53: | ||
Note: This example doesn't work with multiprocessing. | Note: This example doesn't work with multiprocessing. | ||
=References= | =References= |
Latest revision as of 19:39, 9 September 2013
Why Closures 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.