Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #89438

Function decorator having arguments is complicated

Date 2015-04-27 11:37 +0900
Subject Function decorator having arguments is complicated
From Makoto Kuwata <kwa@kuwata-lab.com>
Newsgroups comp.lang.python
Message-ID <mailman.31.1430102277.3680.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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

Back to comp.lang.python | Previous | NextNext in thread | Find similar | Unroll thread


Thread

Function decorator having arguments is complicated Makoto Kuwata <kwa@kuwata-lab.com> - 2015-04-27 11:37 +0900
  Re: Function decorator having arguments is complicated Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2015-04-27 17:36 +1000
    Re: Function decorator having arguments is complicated Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2015-04-29 21:22 +1200

csiph-web