Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #10973
| Date | 2011-08-06 07:19 -0500 |
|---|---|
| From | Tim Chase <python.list@tim.thechases.com> |
| Subject | Re: How do I implement two decorators in Python both of which would eventually want to call the calling function |
| References | <8b087624-4e05-4d2e-bf4f-78383202b7e1@28g2000pry.googlegroups.com> <CAMZYqRQexj2ogtGei9C30qRW0twdAtaAX=Bg0_ZtNbreZv375A@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.1978.1312633195.1164.python-list@python.org> (permalink) |
On 08/06/2011 02:49 AM, Chris Rebert wrote:
> On Fri, Aug 5, 2011 at 10:49 PM, Devraj<devraj@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
Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread
How do I implement two decorators in Python both of which would eventually want to call the calling function Devraj <devraj@gmail.com> - 2011-08-05 22:49 -0700 Re: How do I implement two decorators in Python both of which would eventually want to call the calling function Rafael Durán Castañeda <rafadurancastaneda@gmail.com> - 2011-08-06 09:49 +0200 Re: How do I implement two decorators in Python both of which would eventually want to call the calling function Chris Rebert <clp2@rebertia.com> - 2011-08-06 00:49 -0700 Re: How do I implement two decorators in Python both of which would eventually want to call the calling function Peter Otten <__peter__@web.de> - 2011-08-06 09:59 +0200 Re: How do I implement two decorators in Python both of which would eventually want to call the calling function Tim Chase <python.list@tim.thechases.com> - 2011-08-06 07:19 -0500
csiph-web