help with flexible decorators

J

james_027

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
 
L

Lawrence Oluyede

james_027 said:
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
 
B

Bruno Desthuilliers

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,774
Messages
2,569,598
Members
45,145
Latest member
web3PRAgeency
Top