基本用法:
>>> class A:
def __enter__(self):
print 'in enter'
def __exit__(self, e_t, e_v, t_b):
print 'in exit'
>>> with A() as a:
print 'in with'
in enter
in with
in exit
还有一种用法,使用contextmanager。contextlib是为了加强with语句,提供上下文机制的模块,它是通过Generator实现的。通过定义类以及写__enter__和__exit__来进行上下文管理虽然不难,但是很繁琐。contextlib中的contextmanager作为装饰器来提供一种针对函数级别的上下文管理机制。常用框架如下:
from contextlib import contextmanager
@contextmanager
def make_context() :
print 'in enter'
try :
yield {}
except RuntimeError, err :
print 'error' , err
finally :
print 'in exit'
with make_context() as value :
print 'with' in enter in with in exit