Search code examples
pythongoogle-colaboratorypython-decorators

How do I add an additional print statement for every print statement called in my code? (preferably using code decorators)


I want to check if a print statement is being called and add an additional print statement after it, without having to add an empty print statement manually after every instance. My output is currently like this:

Hello  
Hello  
Hello  
Hello

*(outputs this 10 times)*

while I would like it to look like this:

Hello

Hello

Hello

Hello

*(output 10 times as well in this pattern)*

I preferably want to use decorators as that is the easiest and best-looking solution, but another solution would also be okay!

I tried asking ChatGPT, but it doesn't change anything about the output.

Currently, this is my code:

def readability(func):
  def wrapper(*args,**kwargs):
    result = func(*args, **kwargs)
    if callable(func) and func.__name__ == 'print':
      print(' ')
    return result
  return wrapper

@readability
def printing():
  j=10
  while j>0:
    print('hello')
    j-=1

printing()


Solution

  • Original answer:

    original_print = print
    def print(*args):
        original_print(*args)
        original_print('  ')
    
    print('Hello')
    

    Improved answer using __builtins__:

    def print(*args):
        __builtins__.print(*args)
        __builtins__.print('  ')
    

    Both version produce the following output:

    Hello
    <blank line>