I'm trying to write a simple decorator that adds try/except to any function printing the error.
import random
def our_decorator(func):
def function_wrapper(*args, **kwargs):
try:
func(*args, **kwargs)
except Exception as e:
print(e)
@our_decorator
def test():
for a in range(100):
if a - random.randint(0,1) == 0:
print('success count: {}'.format(a))
pass
else:
print('error count {}'.format(a))
'a' + 1
I keep getting the error:
TypeError: 'NoneType' object is not callable
What am I doing wrong?
The decorator needs to return the wrapper around the decorated function:
import random
def our_decorator(func):
def function_wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
print(e)
return function_wrapper
@our_decorator
def test():
for a in range(100):
if a - random.randint(0,1) == 0:
print('success count: {}'.format(a))
pass
else:
print('error count {}'.format(a))
'a' + 1
As Daniel Roseman correctly noted in the comments: It wouldn't hurt returning the result of the function in the decorator. While it doesn't matter in this specific case, it is usually what you want.