Python while 循环以指数退避重试

Python while loop for retries with exponential back offs

我写了一个函数,它应该多次尝试一个函数直到它起作用。

def Retry(attempts,back_off,value):
    for i in range(attempts):
        counter = 0
        while attempts > counter:
            try:
                x = function(value)
            except:
                counter =+ 1
                delay = (counter * back_off) + 1
                print ('trying again in {} seconds'.format(delay))
                sleep(delay)
                continue
            break
        return x

result = Retry(20,2,value)

每次失败的尝试后都应该有一个指数增长的时间间隔 即 2 秒后第二次尝试,4 秒后第三次尝试,8 秒后第四次尝试,依此类推。问题是,在我编写的函数中,如果第一次尝试失败,我只会得到无限系列的行,如下所示:

trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
trying again in 3 seconds
....

我做错了什么?为什么循环堆在那里?

counter =+ 1

应该是

counter += 1