471,354 Members | 2,060 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,354 software developers and data experts.

help with flexible decorators

Hi,

I want to write a flexible decorators to edit a function that may have
1 or more arguments...

def enhance(func):
def new(x):
#do something ...
return func(x)
return new

@enhance
def method_a(x):
#do something ...

While the enhance decorator work with functions of 1 argument, how do
I make it to work with more than one arguments.

Thanks
james

Aug 7 '07 #1
2 766
james_027 <ca********@gmail.comwrote:
While the enhance decorator work with functions of 1 argument, how do
I make it to work with more than one arguments.
Using *args. Something like this:

def enhance(f):
def _new(*args):
return f(*args) + 1
return _new

@enhance
def f(*args):
return sum(args)

In [22]: f(6)
Out[22]: 7

In [23]: f(6, 4)
Out[23]: 11

In [24]: f(6, 4, 10)
Out[24]: 21
--
Lawrence, oluyede.org - neropercaso.it
"It is difficult to get a man to understand
something when his salary depends on not
understanding it" - Upton Sinclair
Aug 7 '07 #2
james_027 a écrit :
Hi,

I want to write a flexible decorators to edit a function that may have
1 or more arguments...

def enhance(func):
def new(x):
#do something ...
return func(x)
return new

@enhance
def method_a(x):
#do something ...

While the enhance decorator work with functions of 1 argument, how do
I make it to work with more than one arguments.
Use *args (for positional args) and **kw (for keyword args):

def enhance(func):
def new(*args, **kw):
#do something ...
return func(*args, **kw)
return new

@enhance
def method_a(x):
#do something ...
HTH
Aug 7 '07 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

4 posts views Thread by Michael Sparks | last post: by
17 posts views Thread by daishi | last post: by
8 posts views Thread by Michele Simionato | last post: by
4 posts views Thread by RebelGeekz | last post: by
11 posts views Thread by Arien Malec | last post: by
2 posts views Thread by Guido van Rossum | last post: by
13 posts views Thread by km | last post: by
11 posts views Thread by Helmut Jarausch | last post: by
2 posts views Thread by Andrew West | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.