Monday, March 7, 2022

WTF: retry by recursion

 Often, in an application, you'll want to retry some actions when they fail. If you start thinking: "why not use recursion?", stop right there. It's a bad idea. Filling the call stack is never a good idea. It might slow down your whole application. And using Stack Overflow errors to tell you that you should stop retrying is not so great.

Unfortunately for me, someone thought it would be a good idea to introduce this pattern into our production code. Almost everywhere, I find this type of code:

def myfunc(params, tries=0):
    sys.setrecursionlimit(500) #By default 1,000

    try:
        dosomestuff()
    except:
        if tries < sys.getrecursionlimit():
            return myfunc(params, tries+1)
        else:
            print("RECURSION LIMIT HIT for myfunc !")

Please use loops...