【发布时间】:2020-11-06 09:34:26
【问题描述】:
我有异常处理代码被复制并粘贴到多个地方,例如
def get(self, id):
try:
response = self.client_module_property.get(id)
except APIItemNotFoundException:
print("'{}' does not exist.".format(id), file=sys.stderr)
sys.exit(1)
except Exception as e:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(e)
sys.exit(1)
...
还有……
def delete(self, id):
try:
self.client_module_property.delete(id=id)
except APIItemNotFoundException:
print("'{}' does not exist".format(id), file=sys.stderr)
sys.exit(1)
except Exception as e:
print(
"Unknown error. To debug run with env var LOG_LEVEL=DEBUG",
file=sys.stderr,
)
_log.error(e)
sys.exit(1)
我研究过装饰器,但它们对我来说不是一个好选择,因为我正在反省其他代码中的函数参数并且装饰器会更改方法签名。
还有其他方法可以提取异常处理代码以使其可重用吗?
question 中的 cmets 建议可以在此处使用上下文管理器,但我不清楚浏览 python 文档会是什么样子。
该解决方案需要在 Python 2.7 和 3.x 上运行
【问题讨论】:
-
对于 Python 3,您可以使用 functools.wraps 来保留带有装饰器的函数签名。 Reference(即只有 Python 3 解决方案而不是 2.7)。
-
Answer for preserving method signature for Python 2 & 3。 Python 3 使用 functools.wraps 而 Python 2 使用装饰器模块。
标签: python