I love the decorator in Python!!!

Chris Angelico rosuav at gmail.com
Thu Dec 8 11:38:35 EST 2011


On Fri, Dec 9, 2011 at 3:24 AM, K.-Michael Aye <kmichael.aye at gmail.com> wrote:
> I understand this one, it seems really useful. And maybe i start to sense
> some more applicability. Like this, with extra flags that could be set at
> run time, I could influence the way a function is executed without designing
> the function too complex, but by decorating it, which at the end could be
> easier to read than complicated if-then statements in the function.

Right, and less duplication usually results in less bugs, too.
Obviously if you go to any greater level of complexity than this you'd
want to break the lambda out into a proper function, and possibly play
with an indent level (increment on call, decrement on return). You can
also easily add the run-time check, and anything else you want to do,
too. It'll still all be buried away in the definition of trace(), and
on functions that you want to trace, you need still only have "@trace"
and nothing else.

One piece of sophistication that I would rather like to see, but don't
know how to do. Instead of *args,**kwargs, is it possible to somehow
copy in the function's actual signature? I was testing this out in
IDLE, and the fly help for the function no longer gave useful info
about its argument list.

This is why I say that this has almost certainly been done before in a
much better way.

ChrisA



More information about the Python-list mailing list