常用内置模块 contextlib
contextlib模块时关于上下文管理的,在介绍之前需要先介绍一下with语句。 with语句
使用python读写文件时,要特别注意使用完后关闭文件,以免占用资源。正确的关闭文件方法可以用try...finally语句:
try: f = open('\path\to\file', 'r') f.read() finally: if f: f.close()
1 2 3 4 5 6
更为便捷的方法是用with语句:
with open('\path\to\file', 'r') as f: f.read()
1 2
这个with语句是怎么运行的呢?
实际上,在open()里面,包含__enter__()和__exit__()两个方法,我们称拥有这两个方法的对象实现了上下文管理,这种对象就可以使用with语句。下面解析with语句的执行过程:
1.当with语句执行时,执行上下文表达式(即open),尝试获取一个上下文对象; 2.成功获取上下文对象后,调用上下文对象里面的__enter__()方法,如果with语句后有as,则用__enter__()方法的返回值赋值as后的对象 3.做好执行前的准备工作后,开始执行后续代码; 4.当with语句快结束时,调用上下文对象里面的__exit__()方法。在__exit__()方法中有三个参数,如果正常结束,三个参数都为None,如果出现异常,三个参数的值分别等于调用sys.exc_info()函数返回的三个值:类型(异常类)、值(异常实例)和跟踪记录(traceback),相应的跟踪记录对象。
看个例子:
先定义一个有上下文管理的对象A
class A(object): def __enter__(self): print('__enter__() called') return self
def print_hello(self): print("hello world")
def __exit__(self, e_t, e_v, t_b): print('__exit__() called')
1 2 3 4 5 6 7 8 9 10
执行with语句:
with A() as a: # 这里a是__enter__()的返回值 a.print_hello() # 返回self,调用self的print_hello()方法 print('got instance')
1 2 3
运行结果:
__enter__() called hello world got instance __exit__() called
1 2 3 4
@contextmanager
每个要实现上下文管理的对象都要编写__enter__()和__exit__()方法有点繁琐。Python中的contextlib模块提供了更简便的方法。
@contextmanager是一个装饰器decorator,它接收一个生成器generator,把generator里yield的值赋给with...as后的变量,然后正常执行with语句。
from contextlib import contextmanager
class A(object):
def print_hello(self): print('hello world')
@contextmanager def B(): print('Start') a = A() yield a print('Over')
with B() as a: a.print_hello()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
运行结果:
Start hello world Over
1 2 3
我们省去了在对象A里面添加__enter__()和__exit__()方法,改为在外部添加一个装饰器来实现上下文管理。
实际上,在上例中,执行生成器B()的yield之前的语句相当于执行__enter__(),yield的返回值相当于__enter__()的返回值,执行yield之后的语句相当于执行__exit__()。
通过@contextmanager,我们还能实现简单的运行前执行特定代码的功能:
@contextmanager def tag(name): print("<%s>" % name) yield print("</%s>" % name)
with tag("p1"): print("hello") print("world")
1 2 3 4 5 6 7 8 9
运行结果:
<p1> hello world </p1>
1 2 3 4
closing( )
如果一个对象没有实现上下文管理,我们可以直接通过contextlib模块提供的closing( )把对象变为上下文对象然后使用with语句。(前提是这个对象能调用close( )方法!)
如用with语句使用urlopen( ) (以下代码转自廖雪峰官网):
from contextlib import closing from urllib.request import urlopen
with closing(urlopen('https://www.python.org')) as page: for line in page: print(line)
6
实际上,closing也是经过@contextmanager装饰的一个生成器,它内部是这样的:
@contextmanager def closing(thing): try: yield thing finally: thing.close()