[Python-ideas] Syntax for defining parametric decorators

Mike Graham mikegraham at gmail.com
Sun Jul 8 22:22:43 CEST 2012


A common stumbling block for new users is writing decorators that take
arguments. To create a decorator like

@timesn(n)
def f(y):
    ...

We write code like

def timesn(n)
    def decorator(f):
        def inner(y):
            return n * f(y)
        return inner
     return decorator

which confuses many users and can be a handful to type. I wonder if it
would be clearer for people to write

def timesn(n)(f):
    def inner(y):
        return n * f(y)
    return inner

which is more concise and looks a lot more like a non-parametric
decorator someone might have written already. The syntax is mostly
self-explaining and could potentially be useful in other contexts.

There exist tools like the decorator library to try to simplify this
already, but in my experience they mostly serve to confuse people
using decorators for the first time more.

One thing I didn't specify was whether `n` was nonlocal or not and the
behavior of something that keeps and reuses timesn(some_specific_n)
multiple times.

Does anyone think a feature like this may be useful?

Regards,
Mike



More information about the Python-ideas mailing list