上下文管理器

什么是上下文管理器

  • context manager
  • 是一个对象
  • 定义了运行时的上下文
  • 使用with语句来执行

格式:

1
2
3
4
with context as ct:
# 对上下文对象ct的使用

# 上下文对象已经被清除

文件的读写

1
2
3
4
5
6
7
8
# 不用上下文管理器
fileObj = open("file.txt","w")
fileObj.write("This is my file")
fileObj.close()

# 使用上下文管理器
with open("file.txt","w") as fileObj:
fileObj.write("This is my file")
  • 使用with语句,会在代码块结束时,自动帮我们关闭文件,无需手动触发 close()方法
  • with语句,开始前会触发__enter__(self)
  • with语句结束后会触发__exit__(self, exc_type, exc_val, exc_tb)
  • as后面的对象 实际是在调用完__enter__后获取到的返回值

使用上下文管理器实现一个耗时计算函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 不使用上下文管理
nums = [i for i in range(10000)]
random.shuffle(nums)
start = time.perf_counter()
sorted(nums)
end = time.perf_counter()
elapsed = end - start
print(elapsed)

# 使用上下文管理
# 创建一个Timer 上下文管理类
class Timer:
def __init__(self):
self.elapsed = 0

def __enter__(self):
self.start = time.perf_counter()
return self

def __exit__(self, exc_type, exc_val, exc_tb):
self.end = time.perf_counter()
self.elapsed = self.end - self.start

with Timer() as timer:
sorted(nums)

print(timer.elapsed)
  • 应用场景:
    • 文件的开-关
    • 加锁-释放
    • 启动-停止

更新: 2024-01-09 02:16:57
原文: https://www.yuque.com/zacharyblock/cx2om6/ofmfwtiq1h6wysmp