Function decorator having arguments is complicated

Ethan Furman ethan at stoneleaf.us
Mon Apr 27 10:58:37 EDT 2015


On 04/27, Maxime S wrote:
> Le lun. 27 avr. 2015 à 04:39, Makoto Kuwata <kwa at kuwata-lab.com> a écrit :
> >
> > If function decorator notation could take arguments,
> > decorator definition would be more simple:
> >
> >   def multiply(func, n):
> >     def newfunc(*args, **kwargs):
> >       return n * func(*args, **kwargs)
> >     return newfunc
> >
> >   @multiply 4      # ex: @decorator arg1, arg2, arg3
> >   def f1(x, y):
> >     return x+y
> >
> >
> > How do you think about this idea?
> >
> 
> David Beazley has a nice trick [1] to allow optional argument in decorators:
> 
> def logged(func=None, level=logging.DEBUG, message=None):
>     if func is None:
>         return partial(logged, level=level, message=message)
> 
>     @wraps(func)
>     def wrapper(*args, **kwargs):
>         log.log(level, message)
>         return func(*args, **kwargs)
>     return wrapper

That is a cool trick, thanks for sharing!

--
~Ethan~



More information about the Python-list mailing list