我想要編寫使用其他上下文管理上下文管理,因此客戶端不需要知道整個食譜,只是我提出的接口。我無法使用@contextmanager
- 如果由於異常而中斷yield
調用後的代碼不會執行,所以我需要使用基於類的管理器。寫一個上下文管理器在Python本身使用with語句
這裏有一個小例子腳本:
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
{}
有沒有辦法告訴類基於上下文的管理器用其他上下文管理器來包裝自己?
這將會是指定的Python版本是有用的。 – 2012-07-11 20:40:39
不好意思,但你爲什麼要這麼做?對於我來說,基於類的上下文管理器在清除其依賴關係之後應該最後退出,這似乎很自然。 – 2012-07-11 20:44:07
Targeting python 2.7,sorry – 2012-07-12 02:49:13