Python 上下文管理器

上下文管理器用于管理资源,如文件、锁等。

1. with 语句

with open("file.txt") as f:
    content = f.read()
# 自动关闭

2. 类实现

class MyContext:
    def __enter__(self):
        print("Enter")
        return self
    
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exit")
        return False

with MyContext() as ctx:
    print("Inside")

3. 生成器实现

from contextlib import contextmanager

@contextmanager
def my_context():
    print("Enter")
    try:
        yield
    finally:
        print("Exit")

with my_context():
    print("Inside")

4. 异常处理

class Context:
    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_type is ValueError:
            print(f"Caught: {exc_val}")
            return True  # 抑制异常
        return False

5. closing

from contextlib import closing

class Resource:
    def close(self):
        print("Closing")

with closing(Resource()) as res:
    print("Using")

上下文管理器让资源管理更安全。