上下文管理器
配合 Python 的 contexlib 模块里的 @contextmanager 装饰器,yield 也可以用于定义上下文管理器,下面是 Python Tricks 书中的一个例子:
from contextlib import contextmanager
@contextmanager
def managed_file(name):
try:
f = open(name, 'w')
yield f
finally:
f.close()
上面通过装饰器和 yield 关键字定义的上下文管理器和下面类的方法定义等同:
class ManagedFile:
def __init__(self, name):
self.name = name
def __enter__(self):
self.file = open(self.name, 'w')
return self.file
def __exit__(self, exc_type, exc_val, exc_tb):
if self.file:
self.file.close()
可以利用下面的方法分别进行调用:
>>> with ManagedFile('hello.txt') as f:
... f.write('hello, world!')
... f.write('bye now')
>>> with managed_file('hello.txt') as f:
... f.write('hello, world!')
... f.write('bye now')