contextmanager
from contextlib import contextmanager class Query(object): def __init__(self, name): self.name = name def query(self): print('Query info about %s...' % self.name)
@contextmanager
def create_query(name):
print('Begin')
q = Query(name)
try:
yield q
finally:
print('End')
with create_query("zhangsan") as zs:
zs.query()
输出
Begin
Query info about zhangsan...
End
cosling
返回一个在语句块执行完成时关闭 things 的上下文管理器。这基本上等价于
from contextlib import contextmanager @contextmanager def closing(thing): try: yield thing finally: thing.close()
from contextlib import closing from urllib.request import urlopen with closing(urlopen('http://www.python.org')) as page: for line in page: print(line)