我正在尝试编写一个使用其他上下文管理器的上下文管理器,因此客户不需要知道整个配方,只需要知道我正在呈现的界面。我不能这样做@contextmanager
——如果你被异常打断,调用后的代码yield
不会被执行,所以我需要使用基于类的管理器。
这是一个小示例脚本:
from contextlib import contextmanager
import pprint
d = {}
@contextmanager
def simple(arg, val):
print "enter", arg
d[arg] = val
yield
print "exit", arg
del d[arg]
class compl(object):
def __init__(self, arg, val):
self.arg=arg
self.val=val
def __enter__(self):
with simple("one",1):
with simple("two",2):
print "enter complex", self.arg
d[self.arg] = self.val
def __exit__(self,*args):
print "exit complex", self.arg
del d[self.arg]
print "before"
print d
print ""
with compl("three",3):
print d
print ""
print "after"
print d
print ""
输出如下:
before
{}
enter one
enter two
enter complex three
exit two
exit one
{'three': 3}
exit complex three
after
{}
我希望它输出这个:
before
{}
enter one
enter two
enter complex three
{'one': 1, 'three': 3, 'two': 2}
exit complex three
exit two
exit one
after
{}
有没有办法告诉基于类的上下文管理器将自己与其他上下文管理器一起包装?