Python with语句详解:上下文管理器与资源释放
本文深入解析Python中with语句的工作原理及其在资源管理中的应用。通过介绍上下文管理器概念,展示如何利用内置对象、自定义类及contextlib模块实现文件关闭、锁获取等资源的自动清理。文章包含具体代码示例,演示四种典型使用场景,帮助开发者编写更安全、简洁的资源处理代码。
with语句简介与背景
with语句自Python 2.5版本引入,旨在处理与异常相关的资源访问场景。在2.5版本中,需通过`from __future__ import with_statement`导入方可使用;从2.6版本起该功能默认启用(详见What's new in Python 2.6中关于with语句的介绍)。该语句适用于需要确保资源访问安全的场合,无论操作过程中是否发生异常,都能执行必要的“清理”动作以释放资源,例如文件使用后的自动关闭、线程中锁的自动获取与释放等。
核心概念:上下文管理器
术语
使用with语句的前提是理解上下文管理器(Context Manager)的概念。只有实现了上下文管理器协议的对象,才能与with语句配合工作。
资源释放的两种实现方式
在Python中进行资源读写操作后,必须正确释放资源。虽然可以使用try…finally结构来确保资源释放,但Python提供的with语句提供了更简洁的实现方式。
with语句的四种使用场景
1. Python内置的如文件操作open()等函数已可直接支持with语句。
2. 可以自定义支持with语句的对象。
3. 利用contextlib模块也可以创建支持with语句的对象。
4. 针对需要执行close操作的对象,with语句的使用方式。
示例代码中展示了4种不同的使用标注场景。
代码示例:自定义与内置支持
# 自定义支持with语句的对象
class DummyRes:
def __init__(self, tag):
self.tag = tag
def __enter__(self):
print("Enter >>> {}".format(self.tag))
return self
def __exit__(self, exc_type, exc_value, exc_tb):
print("Exit <<< {}".format(self.tag))
if exc_tb is None:
print("Exit without Exception {}".format(self.tag))
return False
else:
print("Exit with Exception {}".format(self.tag))
return True
# 支持closing 上下文with语句对象
class Closing:
def __init__(self, thing):
self.thing = thing
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, exc_tb):
self.thing.close()
class ClosingDemo:
def __init__(self):
self.acquire()
def acquire(self):
print("Acquire RES")
def close(self):
print("Close RES")
from contextlib import contextmanager
class ContextDemo:
def __init__(self):
print("Context Demo init")
raise Exception
print("Context Demo init")
def print(self):
print("Context Demo print 1")
#raise Exception
print("Context Demo print 2")
def close(self):
print("Context Demo close")
def context_demo():
print("context demo in")
raise Exception
print("context demo out")
@contextmanager
def demo():
print("Allocate Resoures")
try:
yield context_demo
finally:
print("raise exception")
#yield "*** contextmanager demo ***"
print("Free Resoures")
if __name__ == "__main__":
# 1. 使用with语句 (自动关闭文件)
with open("test.txt", "w") as f:
f.write("write test")
# 2. 自动定义with语句
with DummyRes("test") as res:
print("With body 1")
raise Exception
print("With body 2")
# 3. 利用contextlib定义with语句
with demo():
print("exc demo")
# 4. closing 上下文 (适合有close操作的情况)
with Closing(ClosingDemo()):
print("Use Resoures")
总结与展望
总结
以上介绍了Python with语句的基本用法,希望能帮助读者理解其原理与应用。如有任何疑问,欢迎留言讨论,小编会及时回复。感谢大家对本站的支持!
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













