I am trying to write a decorator that takes an arbitrary number of functions as positional arguments and then composes these functions with the function that is being decorated.
Conceptually, I am trying to do this:
@format(f1, f2, f3)
def f0(param):
return value
f0(arg)
should evaluate to f3(f2(f1(f0(arg))))
Here is a simple example I have been working on to illustrate the concept.
def lc(s):
s = s.lower()
return s
def punc(s):
if s[-1] != ".":
s = s + "."
return s
else:
return s
def cap(s):
s = s[0].upper() + s[1:]
return s
def format(*args):
def wrapper(func, *a):
for f in args:
func = f(func)
return func
return wrapper
@format(lc, punc, cap)
def example_func(param):
return param
What I'm expecting is this:
f0("MY TEST STRING")
My test string.
I'm getting the following error message:
AttributeError: 'function' object has no attribute 'lower'
There may be an easier way to do this, such as pass the functions directly into the original and not use a decorator, but I am looking for a solution that specifically uses a decorator in this way. Thank you.