[Python-ideas] An easier syntax for writing decorators (& similar things)?

Arnaud Delobelle arno at marooned.org.uk
Mon Oct 8 11:57:12 CEST 2007


On Mon, October 8, 2007 4:33 am, Adam Atlas wrote:
> When writing decorators especially when it's one that needs arguments
> other than the function to be wrapped, it often gets rather ugly...
>
> def dec(a, b, foo=bar):
>      def inner(func):
>          def something(*a, **k):
>              ...stuff...
>              return func(*a, **k)
>          return something
>      return inner
>
> Perhaps we could allow functions to be defined with multiple argument
> lists, basically partially applying the function until all of them
> are filled. (Sort of like currying, but sort of not.)
>
> def dec(a, b, foo=bar)(func)(*a, **k):
>      ...stuff...
>      return func(*a, **k)
>

Whhy not create a (meta-)decorator to do this? Something like:

def decorator_withargs(decf):
    def decorator(*args, **kwargs):
        def decorated(f):
            return decf(f, *args, **kwargs)
        return decorated
    return decorator

Then you can write your decorator as:

@decorator_withargs
def deco(f, a, b, foo='bar'):
    ...stuff...
    return f(...)

I can't try this now (no python) but it seems to me it should work, even
though it makes my head hurt a bit :)  OTOH it might be utterly rubbish.

-- 
Arnaud





More information about the Python-ideas mailing list