I am trying to return the function with arguments and the functions results in the format of the print statement. The code works except I am getting a "None" between each answer when a test is run. How do I prevent the None from printing?
def debug(func):
"""
:param func: function
"""
def inner_func(*args,**kwargs):
answer = func(*args,**kwargs)
return print(f"{func.__name__}{args} was called and returned {answer}")
return inner_func
And the test:
def add(a, b):
return a + b
@debug
def sub(a, b=100):
return a - b
print(add(3, 4))
print(sub(3))`
print(sub(3,4))
add(3, 4) was called and returned 7
None
sub(3,) was called and returned -97
None
sub(3, 4) was called and returned -1
None
Expected Output:
add(3, 4) was called and returned 7
sub(3) was called and returned -97
sub(3, 4) was called and returned -1
I think you meant to write your debug
decorator like this:
(properly indented)
def debug(func):
"""
:param func: function
"""
def inner_func(*args,**kwargs):
answer = func(*args,**kwargs)
print(f"{func.__name__}{args} was called and returned {answer}")
return answer
return inner_func
You meant to return answer
rather than the result of a print()
which is always None
.
Also, if you don't want to see the returned answer
, then don't print it. Since the decorator calls print()
, just call the functions:
add(3, 4)
sub(3)
sub(3,4)
Also, in particular, if you want this line:
sub(3) was called and returned -97
you can change the print line to this:
print(f"{func.__name__}({','.join([str(arg) for arg in args])}) was called and returned {answer}")