[Baypiggies] JJ's decorators
Shannon -jj Behrens
jjinux at gmail.com
Mon Mar 9 07:39:00 CET 2009
On Sun, Mar 8, 2009 at 12:52 AM, Smith1, Robert E
<robert.e.smith1 at lmco.com> wrote:
>>
>> It doesn't. The problem is that there are really two different kinds
> of
>> decorators, those without arguments and those that take an argument.
>> Unfortunately, the second kind is more complicated,
>
> Thanks for the reply. Now that I think about it, I do seem to recall
> Charles Merriam saying that "you get called twice" in the case of
> decorators with arguments. So the first return - "return {"pre":
> pre_logged, "post": post_logged}[when]" - must be to give Python the
> function to call the second time during setup. To my untrained eye it
> looks like the "decorator with arguments" scenario could have been
> handled with a single call that included the decorated function as an
> argument in addition to the arguments for the decorator, but I must be
> missing something.
You can get the decorator package to work like that:
http://pypi.python.org/pypi/decorator
Here's an example from their documentation:
from decorator import decorator
def _trace(f, *args, **kw):
print "calling %s with args %s, %s" % (f.__name__, args, kw)
return f(*args, **kw)
def trace(f):
return decorator(_trace, f)
@trace
def f1(x):
pass
As Charles mentioned, the decorator package will take care of all
those irritating things like making the API match and keeping the
__doc__ in tact.
By the way, don't forget that you can also do tricks like this:
def _trace(f, *args, **kw):
print "calling %s with args %s, %s" % (f.__name__, args, kw)
try:
return f(*args, **kw)
finally:
print "Hmm, well that was fun. You should call f again!"
Best Regards,
-jj
--
In this life we cannot do great things. We can only do small things
with great love. -- Mother Teresa
http://jjinux.blogspot.com/
More information about the Baypiggies
mailing list