'Function to generate a retry with time accumulator every error

I have a main file that calls the secondary:

import code_two

if __name__ == '__main__':
    code_two.main()

file code_two.py:

from random import randint
import time

def try_again(a):
    print(a)
    while True:
        sleep_time += 30
        print('Next attempt in: '+ str(sleep_time/60) + ' minute(s)')
        sleep(sleep_time)
        main(sleep_time=sleep_time)
        return

def main(sleep_time=0):
    try:
        value = randint(0,1)
        if value == 0:
            1/0
    except Exception as e:
        try_again(e)

    try:
        value = randint(2,3)
        if value == 2:
            1/0
    except Exception as e:
        try_again(e)

    try:
        value = randint(4,5)
        if value == 4:
            1/0
    except Exception as e:
        try_again(e)

The error when trying to call the function to retry after an error in the main() function is:

UnboundLocalError: local variable 'sleep_time' referenced before assignment

Since there are three try except and an error can occur in any of the three, I'm trying to make a separate function so the code doesn't get so repetitive and I just need to use try_again(e) instead of all the rest of the code.

Just to clarify, if there is an error, he needs to wait 30 seconds to try again and if there is an error in the new attempt, then he will need to wait 60 seconds (30 from the previous attempt + 30 from the new attempt)



Solution 1:[1]

Move your loop to main, and pass the sleep time to try_again as an argument.

from random import randint
import time


def try_again(a, s):
    print(a)
    print('Next attempt in: '+ str(s/60) + ' minute(s)')
    sleep(s)
    return s + 30


def main(sleep_time=0):
    done = False
    while not done:
        try:
            value = randint(0,1)
            if value == 0:
                1/0
        except Exception as e:
            sleep_time = try_again(e, sleep_time)
            continue
    
        try:
            value = randint(2,3)
            if value == 2:
                1/0
        except Exception as e:
            sleep_time = try_again(e, sleep_time)
            continue
    
        try:
            value = randint(4,5)
            if value == 4:
                1/0
        except Exception as e:
            sleep_time = try_again(e, sleep_time)
            continue

        done = True

Solution 2:[2]

The += operator does not instantiate the object, it assigns a new value to an already created object. Therefore, in the scope of the function try_again(), the interpreter tries to find the variable sleep_time to assign a new value before it has been created.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 chepner
Solution 2 Benjamin Rio