Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #89440
| Date | 2015-04-26 21:24 -0700 |
|---|---|
| From | Ethan Furman <ethan@stoneleaf.us> |
| Subject | Re: Function decorator having arguments is complicated |
| References | <CAFTm5Ru5NbFOtLPoVSPujeakrGawdHXjNkWJOVs1XrvBNnOUOQ@mail.gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.34.1430108682.3680.python-list@python.org> (permalink) |
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
> @multiply(4)
> def f1(x, y):
> return x+y
>
> print(f1(2, 3)) #=> 20 (= 4 * (2+3))
This all works the same.
>
>
> 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?
It's unnecessary, just use a class instead of a function to get more
clarity.
--
~Ethan~
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Function decorator having arguments is complicated Ethan Furman <ethan@stoneleaf.us> - 2015-04-26 21:24 -0700
csiph-web