I have a function that accepts args and kwargs, and I need to do something in my decorator based on the value of the 2nd argument in the function, as in the code below:
def workaround_func(): def decorator(fn): def case_decorator(*args, **kwargs): if args[1] == 2: print('The second argument is a 2!') return fn(*args, **kwargs) return case_decorator return decorator @workaround_func() def my_func(arg1, arg2, kwarg1=None): print('arg1: {} arg2: {}, kwargs: {}'.format(arg1, arg2, kwarg1))
The problem is that python allows users to call a function with a second argument as a regular argument OR a keyword argument, so if a user calls my_func
with arg2
like kwarg, it raises an IndexError
, see below:
In [8]: d.my_func(1, 2, kwarg1=3) The second argument is a 2! arg1: 1 arg2: 2, kwargs: 3 In [9]: d.my_func(1, arg2=2, kwarg1=3) --------------------------------------------------------------------------- IndexError Traceback (most recent call last) <ipython-input-9-87dc89222a9e> in <module>() ----> 1 d.my_func(1, arg2=2, kwarg1=3) /home/camsparr/decoratorargs.py in case_decorator(*args, **kwargs) 2 def decorator(fn): 3 def case_decorator(*args, **kwargs): ----> 4 if args[1] == 2: 5 print('The second argument is a 2!') 6 return fn(*args, **kwargs) IndexError: tuple index out of range
Is there a way around this without doing try/except
and catching an IndexError
?
source share