我正在尝试创建一个类,它将发出api请求,根据传递给retrying.retry
装饰器的配置选项进行重试,并以正确的方式为每个作业处理不同的错误代码。
下面是我的代码:
from retrying import retry
class APIRequester:
def __init__(self, url, **kwargs):
self.url = url
self.retry_kwargs = kwargs
@retry(**self.retry_kwargs) # Obviously doesn't know what self is
def make_request(self):
pass
我如何将参数传递给这个方法装饰器呢?我试着将它们变成一个类属性,但也没有成功。
4条答案
按热度按时间2o7dmzc51#
A couple of notes/questions:
@retry
decorator will be applied to themake_request
method at the time the class is created, whileretry_kwargs
will only become available when an instance of the class is created, and thus the former must precede the latter.In which case, the former cannot depend on information that becomes available in the latter, ... as long as you use the decorator syntax ...
is just syntax sugar for
which means that, along with the fact that Python is very dynamic, you could force the issue by doing something like
Whether this particular decorator chokes on the
self
parameter or not, I cannot tell you.Will you have more than one instance of
APIRequester
? If so, note that the method will be re-decorated each time a new instance is created: can this work sensibly? (I doubt it.) But see the edit below ...If you do not have more that one instance, then you probably don't need to rely on information that becomes availale at the singleton's construction time.
The above were some general Python principles. I doubt that you really want to force the issue in this case. It seems to me that you are trying to use the decorator in a way that it was not designed to be used.
Edit: instancemethods
If you replace the line that does the decorating in the constructor with
then each instance will get its own decorated version of the function. This should avoid any problems with re-decoration of the same function. There may will still be problems with
self
getting in the way. In that case, you could remove theself
parameter from the definition and wrap it withstaticmethod
:Or better still, use decorator syntax to apply
staticmethod
tomake_request
at the place where you define it, the way Guido inteded it.Like this, it even stands a chance of working! :-)
ds97pgxw2#
Decorator只是
func=decorator(func)
的一个语法糖,你可以自己赋值:这将在内部用函数替换方法(描述符),但它将按预期工作。
3ks5zfa03#
当然,self在调用时可以在装饰器中使用,参见对How to decorate a method inside a class?的回答,我的回答基于此:
也就是说,原来的装饰器被一个新的,配置感知的装饰器 Package 。不需要改变构造器,语法保持简单。
lnlaulya4#
重试装饰器不支持类方法,因为类的示例已隐式传递给函数。请装饰普通函数。如果要将函数 Package 到类中,请装饰静态方法。