Suppose I have a function which I have written as a binary-operator (binop), how do I extend it to a multi-operator (multiop) which takes an arbitrary number of arguments? Is there such a decorator in a library (e.g. in functools)?
For example (I want a decorator to give this behaviour):
@binop_to_multiop
def mult(a,b):
return a*b
mult(2,3,4) # 2*3*4 = 24
mult(7) # 7
mult(2,3) # 6
Obviously I can't ask a question about decorators without mentioning, this answer.
.
I've tried writing my own, but can't quite get it working, any explanation of where I'm going wrong would also be welcome:
def binop_to_multiop(f):
@functools.wraps(f)
def wrapper(*args, **kwds):
if len(args) == 1: return args[0] # fails
return f(args[0],(f(*args[1:], **kwds)), **kwds) #recursion attempt fails
return wrapper
Gives a TypeError: mult() takes exactly 2 arguments (N given)
(for various N!=2
).