I am using a function decorator in some unit tests that I am writing to test code. However, I have figured out that this decorator causes the function to be called twice (and therefore print its output twice).
I figured out this error after some functions were returning errant return values that would only happen if a function was called twice.
#!/usr/bin/env python3
def decorate(func):
@wraps(func)
def inner(*args, **kwargs):
print("#" * 40)
print("Testing function {}".format(func.__name__))
print("Arguments passed: {} ".format(args))
print("Begin output of {}".format(func.__name__))
print("#" * 40)
try:
func(*args, **kwargs)
except Exception as e:
print("Error occured: {}".format(e))
print("#" * 40)
print("End of output of {}".format(func.__name__))
print("#" * 40)
print("\n" * 5)
return func(*args,**kwargs) #Error happens on this line here
return inner
#Add decorator to function definition.
@decorate
def asdf():
print("THIS SHOULD PRINT ONCE")
#Call function
asdf()
Output (spacing exactly as copied):
########################################
Testing function asdf
Arguments passed: ()
Begin output of asdf
########################################
THIS SHOULD PRINT ONCE
########################################
End of output of asdf
########################################
THIS SHOULD PRINT ONCE
My desired output:
########################################
Testing function asdf
Arguments passed: ()
Begin output of asdf
########################################
THIS SHOULD PRINT ONCE
########################################
End of output of asdf
########################################
I am trying to eliminate the second calling of the function. I know my error lies in the decorator, I just cannot find it.