python - 将参数传递给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
所以我不确定这是否可能 - 或者我是否应该以不同的方式处理它。
解决方案
如果您只想按原样使用库,那么您不能真正使用这样的装饰器。它的参数从被调用时起是恒定的(除了弄乱可变参数)。相反,您总是可以在每次调用函数之前调用装饰器。这允许您在需要时更改重试参数。
例如。
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=...)
推荐阅读
- reactjs - 当变体是临时的时,样式化的 MUI 抽屉不会打开
- python - 如何在 Python 中将文本文件(每个单独的项目在其自己的行中)读入 2D 列表
- datatables - 如何编辑/更改默认数据表页面消息
- php - 如何将 Laravel 解决方案从 MS SQL Server 迁移到 MySQL
- javascript - 有没有办法在javascript中动态命名普罗米修斯标签?
- xcode - 如何为 Interface Builder 设置环境变量?
- ceph - Ceph 显示大小计算
- html - 背景图像不会在 Bootstrap Studio 的 jumbotron 中显示?
- node.js - 弹性搜索nodejs中的映射器解析异常
- sql - Xaml如何创建条件