Adapting / Sep 20 2022
Python Context Manager
Python的上下文管理器, 可以理解为一个code section的概念:
进入该code section, 需要执行某一个协议 `__enter__()`
离开该code section, 也要执行某一个协议 `__exit__()`
例如, 我要写一个记录我某一个function运行的开始时间和结束时间的上下文管理器:
from datetime import datetimeimport timeclass TimeRecorder: def __enter__(self): print(f'start at: {datetime.now()}') def __exit__(self,exc_type, exc_val, exc_tb): print(f'finished at: {datetime.now()}') def fun(): # do some hard computation time.sleep(5)with TimeRecorder(): fun()5.3s