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


Groups > comp.lang.python > #89441 > unrolled thread

Re: Function decorator having arguments is complicated

Started byChris Angelico <rosuav@gmail.com>
First post2015-04-27 14:32 +1000
Last post2015-04-27 14:32 +1000
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Function decorator having arguments is complicated Chris Angelico <rosuav@gmail.com> - 2015-04-27 14:32 +1000

#89441 — Re: Function decorator having arguments is complicated

FromChris Angelico <rosuav@gmail.com>
Date2015-04-27 14:32 +1000
SubjectRe: Function decorator having arguments is complicated
Message-ID<mailman.35.1430109133.3680.python-list@python.org>
On Mon, Apr 27, 2015 at 2:24 PM, Ethan Furman <ethan@stoneleaf.us> wrote:
> On 04/27, Makoto Kuwata wrote:
>>
>> 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
>
> When I have to write an argument-taking decorator, I use a class:
>
>     class multiply(object):  # don't need 'object in 3.x'
>
>         def __init__(self, n):
>             self.n = n
>
>         def __call__(self, func):
>             def newfunc(*args, **kwargs):
>                 return self.n * func(*args, **kwargs)
>             return newfunc

What's the advantage of that over a simple closure? You have the same
number of nesting levels, plus a lot more boiler-plate repetition -
instead of just referencing names from the outer scope, you have to
explicitly capture them all with "self.n=n" for each one. I'm not sure
you really even gain much clarity.

In a way, a closure is a short-hand for an object with a __call__
method that auto-captures all its local variables.

ChrisA

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web