Reputation: 3
How does one use a decorator to return a given function with all of its arguments modified if the number of arguments is arbitrarily long? I'm tasked with capitalizing all arguments in an input function to a decorator and I can't figure out how to pass an infinite amount of new arguments back into the function.
I'm trying this in theory:
def allCaps(func):
def ret(*args):
return func(*args.upper())
return ret
but you can't mod a tuple so it doesn't work correctly
Upvotes: 0
Views: 86
Reputation: 54163
something like:
def allCaps(func):
def wrapper(*args, **kwargs):
if not all(isinstance(arg,str) for arg in args):
# use isinstance(basestr, arg) for arg in args in python2
raise TypeError("Wrong argument type")
else:
return func(*[arg.upper() for arg in args], **kwargs)
return wrapper
@allCaps
def this_function_needs_allcaps(*args, **kwargs):
print("These are my arguments!")
for arg in args:
print(arg)
Upvotes: 1
Reputation: 36678
You'll want to build a new list (it could be a tuple as well; the Python * syntax just expects an iterable) with the arguments, as follows:
new_args = [arg.upper() for arg in args]
return func(*new_args)
Upvotes: 0