>>> from contextlib import contextmanager
>>> from __future__ import with_statement
>>> @contextmanager
... def context():
... print 'entering the zone'
... try:
... yield
... except Exception, e:
... print 'with an error %s'%e
... raise e
... else:
... print 'with no error'
...
>>> with context():
... print '----in context call------'
...
entering the zone
----in context call------
with no error
使用的最多的就是这个contextmanager, 另外还有一个closing 用处不大
代码如下:
from contextlib import closing
import urllib
with closing(urllib.urlopen('http://www.python.org')) as page:
for line in page:
print line