Function decorator having arguments is complicated

Makoto Kuwata kwa at kuwata-lab.com
Sun Apr 26 22:37:47 EDT 2015


I want to ask Python experts about function decorator which has arguments.

I feel that function decorator having arguments is complicated,
because three 'def' are nested:

  def multiply(n):
    def deco(func):
      def newfunc(*args, **kwargs):
        return n * func(*args, **kwargs)
      return newfunc
    return deco

  @multiply(4)
  def f1(x, y):
    return x+y

  print(f1(2, 3))   #=> 20  (= 4 * (2+3))


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?

--
regards,
makoto kuwata
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150427/829e85d5/attachment.html>


More information about the Python-list mailing list