27 October 2010

Python decorator

It sounds intimidating at first because other OO languages like C++ or Java doesn't have such concept or construct built in. So what's about it?

def dec_func():
   ...

@dec_func
def func():
   ...


function 'func' is being decorated by function 'dec_func'; it is equivalent to "func = decf_func(func)".


The key concept is this:

@ is just a little syntax sugar meaning "pass a function object through another function and assign the result to the original function."

It brings the idea of "applying code to other code" (i.e.: like C macros) into mainstream thinking by formalizing it as a language construct. See the link

No comments: