Reputation: 87
I would like to check and change, if necessary, the type of a function's parameter with decorator, i.e. something like that:
def convert_argument_types(func):
def inner(*args):
for arg in args:
if not isinstance(arg, something):
arg = convertToSomething(arg)
return func(*args)
return inner
@convert_argument_types # I would like to apply it to functions with unknown number of parameters
def someFunction(arg1, arg2):
pass
I tried of course within the inner function the following:
return func(args)
But it doesn't work, doesn't change the type of *args.
Of course, by knowing the number of parameters, I could do for each number of parameters smg like:
def convert_two_argument_types(func):
def inner(arg, arg2):
if not isinstance(arg, something):
arg = convertToSomething(arg)
if not isinstance(arg2, something):
arg2 = convertToSomething(arg2)
return func(arg, arg2)
return inner
with convert_one/two/three/etc_argument_types(), but it is everything, but not elegant.
Is there a way to solve my issue by using decorators? What would be the most elegant way?
Thank you for your help!
Upvotes: 0
Views: 1239
Reputation: 781059
Assigning to arg
has no effect on args
; the variable gets a reference to the value of the tuple element, not a reference to the tuple itself.
In addition, since tuples are immutable, you can't modify it in place.
Use a list comprehension to make a new list with the modified values.
args = [arg if isinstance(arg, something) else convertToSomething(arg) for arg in args]
Upvotes: 1