[Python-ideas] Proposal for new-style decorators

Christophe Schlick cschlick at gmail.com
Wed Apr 27 03:58:24 CEST 2011


On Wed, Apr 27, 2011 at 12:30 AM, Chris Rebert <pyideas at rebertia.com> wrote:
> On Tue, Apr 26, 2011 at 10:10 AM, Christophe Schlick <cschlick at gmail.com> wrote:
>> @decorator
>> ...
>> @decorator(n=3, trace=True)
>>...
>
> I'm personally not a fan of magic such as having both @decorator and
> @decorator(...) work.

Well, you may simply use @decorator(), if your decorator does not need
arguments. Actually the magic does not come from the new 'decorator'
class, but directly from the state machine used to parse the @-syntax
in Python. I am not responsible for that.

> What if my decorator's parameters don't all have default values?
> What if I don't want people to have to use keyword arguments when
> using my decorator?
> What if my decorator accepts extra positional arguments (i.e. *args)?

The idea behind the proposal is to reduce the boilerplate for most of
the standard patterns of decorators. One element of that reduction is
to automatically transform the decorator arguments as attributes of
the decorated function. To do this, the attributes have to get
individual names, that's why I've proposed the keyword argument
syntax. However, it is actually possible to implement the same idea by
letting the decorator use positional arguments, which are then
combined into a single tuple attribute 'self.args' available for the
decorating function. The code of the 'decorator' class would simply be
a bit longer, but there is no specific difficulty here.

 CS



More information about the Python-ideas mailing list