gpt4 book ai didi

python - 如何将装饰器与@contextmanager 装饰器混合使用?

转载 作者:行者123 更新时间:2023-11-28 18:54:50 25 4
gpt4 key购买 nike

这是我正在使用的代码:

from contextlib import contextmanager
from functools import wraps
class with_report_status(object):

def __init__(self, message):
self.message = message

def __call__(self, f):
@wraps(f)
def wrapper(_self, *a, **kw):
try:
return f(_self, *a, **kw)
except:
log.exception("Handling exception in reporting operation")
if not (hasattr(_self, 'report_status') and _self.report_status):
_self.report_status = self.message
raise

return wrapper

class MyClass(object):

@contextmanager
@with_report_status('unable to create export workspace')
def make_workspace(self):
temp_dir = tempfile.mkdtemp()
log.debug("Creating working directory in %s", temp_dir)
self.workspace = temp_dir
yield self.workspace
log.debug("Cleaning up working directory in %s", temp_dir)
shutil.rmtree(temp_dir)

@with_report_status('working on step 1')
def step_one(self):
# do something that isn't a context manager

问题是,@with_report_status 没有像 @contextmanager 预期的那样产生结果。但是,我也不能将它换成其他方式,因为 @contextmanager 返回一个生成器对象(我认为!)而不是值本身。

如何让 @contextmanager 与装饰器一起使用?

最佳答案

尝试将@contextmanager 移到装饰器列表的底部。

关于python - 如何将装饰器与@contextmanager 装饰器混合使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4731811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com