Python 在函数中使用decorator

Python 在函数中使用decorator,python,python-decorators,Python,Python Decorators,在函数内部,我使用的重试机制如下(总是在try/except块中): 如果是的话,你能帮我举一个装饰师做这类工作的例子吗 decorator语法只是对 # f could be a class as well def f(): ... f = retry(f) 它不能应用于任意匿名代码块。装饰程序的主要目的是重新绑定一个名称,根据定义,匿名块没有名称 您需要做的是将要重试的代码重构为一个经过修饰的函数。比如说, @retry(max=5, message='blablabla') de

在函数内部,我使用的重试机制如下(总是在try/except块中):


如果是的话,你能帮我举一个装饰师做这类工作的例子吗

decorator语法只是对

# f could be a class as well
def f():
    ...
f = retry(f)
它不能应用于任意匿名代码块。装饰程序的主要目的是重新绑定一个名称,根据定义,匿名块没有名称

您需要做的是将要重试的代码重构为一个经过修饰的函数。比如说,

@retry(max=5, message='blablabla')
def get_lock():
    try:
        cu.lock()
    except LockError as l_error:
        # Some action dependent on the implementation of retry


def load(self):
    get_lock()

如上所述,decorator只能应用于函数,但可以将“重试”逻辑移动到单独的函数,并将
cu.lock
/
cu.unlock
(以及其他类似
max
messge
)作为参数传递到该函数:

def retry(func, tries, message):
    for i in range(1, tries+1):                        
        try:
            func()  # <- call passed function
            break
        except LockError as l_error:
            if i < tries:
                sleep(20)
                continue
            else:
                raise ContinuableError('...')

def load(self):
    retry(cu.lock, tries=5, message='blablabla')  # pass cu.lock to be called

    retry(cu.unlock, tries=5, message='blablabla')  # pass cu.unlock to be called
def重试(函数、重试、消息):
对于范围(1,尝试+1)中的i:
尝试:

func()#修饰符只对函数起作用。还有,为什么不在这里使用一个方法并将重试参数作为参数传递呢?看起来您每次都试图运行相同的代码。@Kurtststutsman-我不确定OP的具体用例,但我知道我见过一些旧代码,其中
重试部分是在许多函数上完成的,而重试与底层功能无关(
锁定
解锁
更新
删除
,等等-数据库命令或其他)。这似乎是使用
decorator
功能的完美用例,而不是将10个方法与
maxRetries
混为一谈。也就是说,您的第一句话很正确,OP需要向前推进。感谢您的回答,我将尝试这种方法
@retry(max=5, message='blablabla')
def get_lock():
    try:
        cu.lock()
    except LockError as l_error:
        # Some action dependent on the implementation of retry


def load(self):
    get_lock()
def retry(func, tries, message):
    for i in range(1, tries+1):                        
        try:
            func()  # <- call passed function
            break
        except LockError as l_error:
            if i < tries:
                sleep(20)
                continue
            else:
                raise ContinuableError('...')

def load(self):
    retry(cu.lock, tries=5, message='blablabla')  # pass cu.lock to be called

    retry(cu.unlock, tries=5, message='blablabla')  # pass cu.unlock to be called