On 08/06/2011 02:49 AM, Chris Rebert wrote:
On Fri, Aug 5, 2011 at 10:49 PM, Devraj<dev...@gmail.com>  wrote:
My question, how do I chain decorators that end up executing the
calling method, but ensure that it's only called once.

That's how it works normally; decorators stack (and order is therefore
important). With normal wrapping decorators, only the first decorator
gets access to the original function and is able to call it.

I'd clarify "first decorator" here as the one closest to the decorated function which is actually the *last* one in the list of decorators, but first-to-decorate. In Chris's example below, decorator_A is the only one that calls myfunc().

Subsequent decorators only get access to the already-wrapped function.

Example:

def decorator_A(func):
     def decorated(*args, **kwds):
         print "In decorator A"
         return func(*args, **kwds)
     return decorated

def decorator_B(func):
     def decorated(*args, **kwds):
         print "In decorator B"
         return func(*args, **kwds)
     return decorated

@decorator_B
@decorator_A
def myfunc(arg):
     print "hello", arg

myfunc('bob')
In decorator B
In decorator A
hello bob


Notice that myfunc() only got executed once.

-tkc



--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to