前戏
在Python中,读写文件这样的资源要特别注意,必须在使用完毕后正确关闭它们。正确关闭文件资源的一个方法是使用try...finally:
try:
f = open('/path/to/file', 'r')
f.read()
finally:
if f:
f.close()
并不是只有open()函数返回的fp对象才能使用with语句。实际上,任何对象,只要正确实现了上下文管理,就可以用于with语句。
实现上下文管理是通过__enter__和__exit__这两个方法实现的
class Query:
def __init__(self, name):
self.name = name
def __enter__(self):
print('begin')
return self
def __exit__(self, exc_type, exc_val, exc_tb):
if exc_type:
print('error')
else:
print('end..')
def query(self):
print(f'i am {self.name}...')
with Query('Bob') as q:
q.query()
输出
begin
i am Bob...
end..
@contextmanager
编写__enter__和__exit__仍然很繁琐,因此Python的标准库contextlib提供了更简单的写法,上面的代码可以改写如下:
from contextlib import contextmanager
class Query:
def __init__(self, name):
self.name = name
def query(self):
print(f'i am {self.name}')
@contextmanager
def func(name):
print('begin..')
q = Query(name)
yield q
print('end')
with func('sb') as f:
f.query()
输出
begin..
i am sb
end
总结
代码的执行顺序是:
with语句首先执行yield之前的语句,因此打印出<h1>;
yield调用会执行with语句内部的所有语句,因此打印出hello和world;
最后执行yield之后的语句,打印出</h1>。
因此,@contextmanager让我们通过编写generator来简化上下文管理。
@closing
如果一个对象没有实现上下文,我们就不能把它用于with语句。这个时候,可以用closing()来把该对象变为上下文对象。
from contextlib import closing
from urllib.request import urlopen
with closing(urlopen('https://www.python.org')) as page:
for line in page:
print(line)
closing也是一个经过@contextmanager装饰的generator,这个generator编写起来其实非常简单
@contextmanager
def closing(thing):
try:
yield thing
finally:
thing.close()
转载自https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001478651770626de401ff1c0d94f379774cabd842222ff000