Python上下文管理器:告别繁琐的资源清理
在Python开发中,我们经常需要处理资源管理——打开文件、连接数据库、获取锁等。传统的方式是使用try-finally块确保资源被正确关闭,但Python提供了一个更优雅的解决方案:上下文管理器。
问题场景
想象一下典型的文件操作:
file = open('data.txt', 'r')
try:
data = file.read()
finally:
file.close()
with语句的魔力
使用上下文管理器和with语句,代码变得简洁明了:
with open('data.txt', 'r') as file:
data = file.read()
# 文件在这里自动关闭
创建自定义上下文管理器
你可以通过类实现自己的上下文管理器:
class DatabaseConnection:
def __init__(self, connection_string):
self.conn_string = connection_string
def __enter__(self):
self.conn = create_connection(self.conn_string)
return self.conn
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
if exc_type:
print(f"异常发生: {exc_val}")
return False # 不抑制异常
# 使用方式
with DatabaseConnection('localhost:5432') as db:
result = db.query('SELECT * FROM users')
contextlib简化版
对于简单场景,可以使用contextlib模块:
from contextlib import contextmanager
@contextmanager
def timer():
start = time.time()
try:
yield
finally:
print(f"耗时: {time.time() - start}秒")
with timer():
time.sleep(1.5)
上下文管理器不仅使代码更简洁,还确保了资源的正确释放,减少了内存泄漏的风险。掌握这一特性,你的Python代码将更加健壮和专业。