I have a question about adding delay after calling various functions.
Let's say I've function like:
def my_func1():
print("Function 1")
def my_func2():
print("Function 2")
def my_func3():
print("Function 3")
Currently I've added delay between invoking them like below:
delay = 1
my_func1()
time.sleep(delay)
my_func2()
time.sleep(delay)
my_func3()
time.sleep(delay)
As you can see I needed a few times time.sleep, which I would like to avoid.
Using decorator is also not an option, since it might be that I would like to avoid delay when calling one of this function not in a group.
Do you have any tip how to beautify this?
Not sure if I know what you mean but you could try:
functions = [my_func1, my_func2, my_func3]
for func in functions:
func()
time.sleep(1)
You can define something like this:
def delay_it(delay, fn, *args, **kwargs):
return_value = fn(*args, **kwargs)
time.sleep(delay)
then
a = delay_it(1, my_func1, "arg1", arg2="arg2")
b = delay_it(1, my_func2, "arg3")
...
I've tested this based on "How to Make Decorators Optionally Turn On Or Off" (How to Make Decorators Optionally Turn On Or Off)
from time import sleep
def funcdelay(func):
def inner():
func()
print('inner')
sleep(1)
inner.nodelay = func
return inner
@funcdelay
def my_func1():
print("Function 1")
@funcdelay
def my_func2():
print("Function 2")
@funcdelay
def my_func3():
print("Function 3")
my_func1()
my_func2()
my_func3()
my_func1.nodelay()
my_func2.nodelay()
my_func3.nodelay()
Output:
Function 1
inner
Function 2
inner
Function 3
inner
Function 1
Function 2
Function 3
You can see that it can bypass the delay.
It's not a good way to handle delay in a function; because each function should do only one thing.
Dont't do this:
def my_func(delay):
# do stuff
if delay>0:
time.sleep(delay)
Try to make a delay handler function and put suitable delay after each function you pass to it.
Try this:
def delay_handler(functions_list,inputs_list,delay_list):
for function,cur_input,delay in zip(functions_list,inputs_list,delay_list):
function(*cur_input)
time.sleep(delay)
Tip 1: Zip will iterate throw each list (any iterable) simultaneously; first elements in inputs_list and delay_list are for first function in function_list and etc.
Tip 2: The '*' behind a list will unpack it.