[Python-ideas] Proposal for new-style decorators

Chris Rebert pyideas at rebertia.com
Wed Apr 27 00:30:48 CEST 2011


On Tue, Apr 26, 2011 at 10:10 AM, Christophe Schlick <cschlick at gmail.com> wrote:
<snip>
> Part 2 - The new-style syntax for decorators:
>
> Here is the code of the same decorators as in Part 1 above, but the
> proposed syntax. The first decorator ('new_style_repeat_fix') is
> created without parameters, while the second one
> ('new_style_repeat_var') uses arguments 'n' and 'trace' with the same
> role as previously:
>
> #---
> @decorator
> def new_style_repeat_fix(self, *args, **keys):
>  """docstring for decorating function"""
>  print "apply %r on %r" % (self.deco.__name__, self.func.__name__)
>  for n in range(3): self.func(*args, **keys)
>
> @decorator(n=3, trace=True)
> def new_style_repeat_var(self, *args, **keys):
>  """docstring for decorating function"""
>  if self.trace:
>    print "apply %r on %r" % (self.deco.__name__, self.func.__name__)
>  for n in range(self.n): self.func(*args, **keys)

I'm personally not a fan of magic such as having both @decorator and
@decorator(...) work.

> When examining the new-style syntax, one can notice that there are
> basically four characteristics that distinguish NSD from OSD:
>
> * Each NSD is decorated by a newly-introduced callable class called
> 'decorator' (code provided in Part 3) by using one of two possible
> decorating forms. The first form '@decorator' is employed for
> decorators that do not need any parameter. The second form
> '@decorator(arg1=val1, arg2=val2...)' is employed to specify a
> sequence of named arguments (combined with their default values) that
> are passed to the decorator using the standard notation for keyword
> arguments.

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)?

Cheers,
Chris



More information about the Python-ideas mailing list