Monday 10 September 2012

Python Decorators

Python Decorator is a strategic use of functional programing facilities. Decoration stands for some kind of modifications. Let us consider one example. Consider , we have some function takes one integer and maps to some other integer, take a squaring function for now.
>>> def square(x):
...     return x*x
and we have to make a generalized function which accepts functions of the above kind as arguments and produce new function which do some further maping. take a doubling method for now.
>>> def double(x):
...     return x*2
Now let us make a function mofifier function
>>> def modify(f):
...     def g(x):
...             return double(f(x))
...     return g
now we can have a new function which performs the two mappings squaring and doubling together

command
>>> newFun=modify(square)
>>> newFun(2)
8
we can generalize the use of such function modifying functions with concept of decorators as
>>> @modify
... def square(x):
...     return x*x
 now we have a modified version of function square(x)
>>> square
<function g at 0x93dc64c>
>>> square(2)
8
Just after defining the function square, it is passed to modify() and the result returned is used instead of square().
>>> def decGenerate(mapping):
...     def modify(f):
...             def g(x):
...                     return mapping(f(x))
...             return g
...     return modify
... 
>>> @decGenerate(double)
... def square(x):
...     return x*x
... 
>>> square(2)
8
Here function decGenerator(mappingFunction) returns a function makung functio modify(f) which can be used as decorator



No comments:

Post a Comment