[Python-ideas] Syntax for defining parametric decorators

Joao S. O. Bueno jsbueno at python.org.br
Mon Jul 9 15:14:26 CEST 2012


On 9 July 2012 09:28, Calvin Spealman <ironfroggy at gmail.com> wrote:
> On Sun, Jul 8, 2012 at 4:22 PM, Mike Graham <mikegraham at gmail.com> wrote:
>> A common stumbling block for new users is writing decorators that take
>> arguments. To create a decorator like
>>
>> @timesn(n)
>> def f(y):
>>     ...


-1 for the new syntax, since a  decorator for trivial decorator factories
(rather, parameterized decorators) can be written in a total of 5 lines:


from functools import partial

def parameterized(decorator):
    def part_decorator(*args, **kw):
        return partial(decorator, *args, **kw)
    return part_decorator

>>> @parameterized
... def times(n, func):
...     def new_func(*args, **kw):
...         return n * func(*args, **kw)
...     return new_func
...
>>>
>>> @times(3)
... def add(x ,y):
...     return x + y
...
>>> add(1,1)
6
-------
For more complex cases, requiring pre processing, post processing, and
so on, the normal syntax can cut it.
And, certainly, a more complex such decorator could be written, so
that it accepts some arguments itself.

(I would be +1 for such a decorator in functools)

  js
 -><-



More information about the Python-ideas mailing list