1

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

1 Answers1

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}")
quamrana
  • 37,849
  • 12
  • 53
  • 71
  • Corrected the indent, but when I return answer I then get the total between lines. – Gregory Morris Jul 30 '22 at 15:46
  • (Don't mind that your question is closed. You have now supplied everything that is needed: Your code properly indented. They way you use the code. The current output. The expected output. We need ask nothing more of you. You have my +1). – quamrana Jul 30 '22 at 15:56
  • Thank you took me moment to realize, the mistake you pointing out is I just needed to return the formatted string and exclude the print. I appreciate the quick replays. – Gregory Morris Jul 30 '22 at 17:50