I’m learning decorators and here I’m trying to change the below to decorator pattern.
def invert(x):
return 1/x
print invert(5)
can be changed using decorators.
def safe(fun, *args):
if args[0]!=0:
return fun(*args)
else:
"Division by 0"
def invert(x):
return 1/x
print safe(invert, 5)
Using @wapper syntax,
def safe(fun, *args):
if args[0]!=0:
return fun(*args)
else:
"Division by 0"
@safe
def invert(x):
return 1/x
print invert(5)
The above code gives error IndexError: tuple index out of range. I’m trying to understand what makes it wrong and how to correct it.
Your main problem is that a decorator needs to return a function, not a value. The decorator replaces the defined function with a new one based on it.
Beyond that, you do not have a
returnstatement in theelseblock, merely a string literal. You probably meant to return that.Just as a note, I presume this is for the purposes of the exercise only, but errors should not pass silently in Python – the behaviour of emitting an exception is far more useful in general than returning a string on error. In fact, to implement this more naturally for Python you want to follow a ask for forgiveness, not permission mantra:
Also, be careful of sweeping statement names like ‘safe’ – other exceptions could still be thrown.