with和contgextlib
应用场景
即使运行失败也要退出,比如:
- 关闭一个文件
- 释放一个锁
- 创建一个临时的代码补丁
- 在特殊环境中运行受保护的代码
with语句和上下文协议
最常用的是打开和关闭一个文件
|
|
实现with的协议如下:
|
|
output12345entering the zonei an the zoneleaving the zoneno error[Finished in 0.1s]
在py中,一个类实现两个方法 __enter__
和__exit__
,就实现了with协议,thread
和threading
模块的一些类也实现了这些方法
thread.LockType
threading.Lock
threading.RLock
threading.Condition
threading.Semaphore
threading.BoundedSemaphore
contextlib模块
给with提供了一个辅助类,包含了一yield分开的__enter__
和__exit__
,所以上面的离职可以写成12345678910111213141516from contextlib import contextmanager# from __future__ import with_statement@contextmanagerdef 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("starting")