from contextlib import contextmanager @contextmanager def tag(name): print "<%s>" % name yield print "</%s>" % name >>> with tag("h1"): ... print ("foo") ... <h1> foo </h1>
编写 __enter__ 和 __exit__ 仍然很繁琐,因此Python的标准库 contextlib 提供了更简单的写法
@contextmanager 这个装饰器接受一个 generator,用 yield 语句把 with ... as var 把变量输出出去,然后,with 语句就可以正常的工作了
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) yield q print('End')
with create_query('Bob') as q: q.query()