0

Hi so I'm creating a text-based game with Python and I want to make it so that before each print statement there is a one second delay.

My current solution is to do this:

time.sleep(1)
name = input('Do you happen to remember what your name was? ').capitalize()
print(name + ", that's a nice name.")
time.sleep(1)
print("Well it seems that you are all better now so I'm going to have to let you go")

However, it is annoying to put a time.sleep before each print!

So I'm wondering if anyone knows a more efficient way of doing this.

Nishant
  • 20,354
  • 18
  • 69
  • 101
Bob Bob
  • 13
  • 2

3 Answers3

1

why not use function to do it?

def dprint(s, delay=1):
    time.sleep(delay)
    print(s)

Is it ok for you?

dprint("hello")
pwxcoo
  • 2,903
  • 2
  • 15
  • 21
1

You could patch the print() function using mock.patch() like this if you need this functionality to be temporary but for all print() function subcalls:

import time
from unittest import mock

OLD_PRINT = print

def make_delayed_print(delay):

    def delayed_print(*args, **kwargs):
        time.sleep(delay)
        OLD_PRINT(*args, **kwargs)

    return delayed_print


with mock.patch('builtins.print', make_delayed_print(1)):
    print(1)
    print(2)
leotrubach
  • 1,509
  • 12
  • 15
0

Here's how I would do it, which will support all existing calls to print() without changing the name of the function being called to something else and it supports multiple arguments and keyword arguments (just like the regular print() function does):

import time

DELAY = 1
regular_print = print  # Save built-in function.

def print(*args, **kwarg):
    time.sleep(DELAY)
    regular_print(*args, **kwarg)
martineau
  • 119,623
  • 25
  • 170
  • 301