Python上下文管理器(context manager)

时间:2023-03-09 19:30:32
Python上下文管理器(context manager)
  • 上下文管理器(context manager)是Python2.5开始支持的一种语法,用于规定某个对象的使用范围。一旦进入或者离开该使用范围,会有特殊操作被调用 (比如为对象分配或者释放内存)。它的语法形式是with...as...

# with context manager
with open("new.txt", "w") as f:
print(f.closed)
f.write("Hello World!")
print(f.closed)

如果用正常的open,close

# without context manager
f = open("new.txt", "w")
print(f.closed) # whether the file is open
f.write("Hello World!")
f.close()
print(f.closed)

上下文管理的好处:

两段程序实际上执行的是相同的操作。我们的第一段程序就使用了上下文管理器 (with...as...)。上下文管理器有隶属于它的程序块。当隶属的程序块执行结束的时候(也就是不再缩进),上下文管理器自动关闭了文件 (我们通过f.closed来查询文件是否关闭)。我们相当于使用缩进规定了文件对象f的使用范围。