By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,172 Members | 762 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,172 IT Pros & Developers. It's quick & easy.

help with flexible decorators

P: n/a
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
Share this Question
Share on Google+
2 Replies


P: n/a
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

P: n/a
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.