from contextlib import contextmanager @contextmanager def context(): print "entering" yield print "exiting" def test(): with context(): for x in range(10): yield x for x in test(): if x == 5: break # or raise
输出:
entering
当循环中断时,有没有办法使python自动调用上下文()的__exit__方法?还是其他一些实现同样目标的方法?我对于生成器和上下文管理器的了解使我怀疑这是不可能的,但是这使得内部管理器在生成器中是没有用的,不是吗?在我看来,一个块中的yield语句应该会引发一个红旗,上下文管理器__exit__可能不会运行.
解决方法@H_403_12@
那么你可以用一个try / finally子句将context()函数中的yield包装起来:
from contextlib import contextmanager
@contextmanager
def context():
print "entering"
try:
yield
finally:
print "exiting"
def test():
with context():
for x in range(10):
yield x
for x in test():
if x == 5:
break # or raise
输出:
entering
exiting
编辑:如果您尝试:help(contextmanager),它将显示它的“典型”使用示例,它们用yield / finally子句包装yield.
from contextlib import contextmanager @contextmanager def context(): print "entering" try: yield finally: print "exiting" def test(): with context(): for x in range(10): yield x for x in test(): if x == 5: break # or raise
输出:
entering exiting
编辑:如果您尝试:help(contextmanager),它将显示它的“典型”使用示例,它们用yield / finally子句包装yield.