首页 > 解决方案 > 将参数传递给python中的装饰器

问题描述

我正在使用包retrying中的重试功能。我想retry从函数传递装饰器的参数,但我不知道如何实现。

@retry # (wait_exponential_multiplier=x,wait_exponential_max=y)
def post(url, json, exponential_multiplier, exponential_max):
    ...
    return(abc)

我想retry在调用post(). 我知道当function编译时,结果function对象被传递给decorator所以我不确定这是否可能 - 或者我是否应该以不同的方式处理它。

标签: pythondecoratorpython-decorators

解决方案


如果您只想按原样使用库,那么您不能真正使用这样的装饰器。它的参数从被调用时起是恒定的(除了弄乱可变参数)。相反,您总是可以在每次调用函数之前调用装饰器。这允许您在需要时更改重试参数。

例如。

def post(url, json):
    ...

rety(post, wait_exponential_multiplier=...)(url=..., json=...)

但是到那时,您不妨完全跳过装饰器,并使用装饰器正在使用的东西。

from retrying import Retrying

def post(url, json):
    ...

Retrying(wait_exponential_multiplier=...).call(post, url=..., json=...)

这些方法中的任何一种都允许您保持post函数的纯净和抽象,远离重试的概念(post当您不想重试行为时更容易调用)。

您还可以编写一个方便的函数来填充程序的默认值。例如。

def retrier(wait_exponential_multiplier=2, **kwargs):
    return Retrying(wait_exponential_multiplier=wait_exponential_multiplier, **kwargs)

retrier(wait_exponential_max=10).call(post, url=..., json=...)
retrier(wait_exponential_multiplier=3, wait_exponential_max=10).call(post, url=..., json=...)

推荐阅读