Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #89460 > unrolled thread
| Started by | Maxime S <maxischmeii@gmail.com> |
|---|---|
| First post | 2015-04-27 14:42 +0000 |
| Last post | 2015-04-27 14:42 +0000 |
| 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.
Re: Function decorator having arguments is complicated Maxime S <maxischmeii@gmail.com> - 2015-04-27 14:42 +0000
| From | Maxime S <maxischmeii@gmail.com> |
|---|---|
| Date | 2015-04-27 14:42 +0000 |
| Subject | Re: Function decorator having arguments is complicated |
| Message-ID | <mailman.46.1430145739.3680.python-list@python.org> |
[Multipart message — attachments visible in raw view] — view raw
Le lun. 27 avr. 2015 à 04:39, Makoto Kuwata <kwa@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
I think that solve your problem nicely, and that it is quite readable.
[1] Amongst a heap of other cool tricks, in his Python Cookbook
Regards,
Maxime
Back to top | Article view | comp.lang.python
csiph-web