雅喜互研

雅喜互研

contextlib.contextmanager(上下文管理器装饰器)

26
2025-02-26

简介

contextlib.contextmanager 是 Python 标准库 contextlib 模块中的一个装饰器,用于简化上下文管理器的创建。它允许你通过一个生成器函数来定义上下文管理器的行为,而无需显式实现 __enter____exit__ 方法。

语法

Python复制

from contextlib import contextmanager

@contextmanager
def context_manager_function(*args, **kwargs):
    # 进入上下文时的代码
    yield
    # 退出上下文时的代码

参数说明

  • context_manager_function:一个生成器函数,定义了上下文管理器的行为。
  • yield:在生成器中,yield 语句将上下文管理器的控制权交给 with 语句块中的代码。yield 之前的代码在进入上下文时执行,yield 之后的代码在退出上下文时执行。

返回值

context_manager_function 返回一个上下文管理器对象,该对象可以用于 with 语句。

示例及解释

  1. 创建一个简单的上下文管理器

    Python复制

    from contextlib import contextmanager
    
    @contextmanager
    def my_context_manager():
        print("Entering the context")
        yield
        print("Exiting the context")
    
    with my_context_manager():
        print("Inside the context")
    

    解释:在这个例子中,my_context_manager 是一个生成器函数,它使用 @contextmanager 装饰器定义了一个上下文管理器。yield 之前的代码在进入上下文时执行,yield 之后的代码在退出上下文时执行。

    输出:

    复制

    Entering the context
    Inside the context
    Exiting the context
    
  2. 传递参数给上下文管理器

    Python复制

    @contextmanager
    def my_context_manager(name):
        print(f"Entering the context: {name}")
        yield
        print(f"Exiting the context: {name}")
    
    with my_context_manager("MyContext"):
        print("Inside the context")
    

    解释:在这个例子中,my_context_manager 接受一个参数 name,并在进入和退出上下文时打印它。

    输出:

    复制

    Entering the context: MyContext
    Inside the context
    Exiting the context: MyContext
    
  3. 处理异常

    Python复制

    @contextmanager
    def my_context_manager():
        try:
            print("Entering the context")
            yield
        except Exception as e:
            print(f"An error occurred: {e}")
        finally:
            print("Exiting the context")
    
    with my_context_manager():
        raise ValueError("Something went wrong")
    

    解释:在这个例子中,my_context_manager 使用 try...except 块来捕获异常,并在 finally 块中确保退出上下文时的代码被执行。

    输出:

    复制

    Entering the context
    An error occurred: Something went wrong
    Exiting the context
    

注意事项

  • 使用 contextlib.contextmanager 可以快速创建上下文管理器,而无需显式实现 __enter____exit__ 方法。
  • yield 语句将上下文管理器的控制权交给 with 语句块中的代码。yield 之前的代码在进入上下文时执行,yield 之后的代码在退出上下文时执行。
  • 如果需要处理异常,可以在生成器函数中使用 try...except 块。
  • contextlib.contextmanager 是一个非常灵活的工具,适用于简单的上下文管理器场景。对于更复杂的场景,可能需要显式实现 __enter____exit__ 方法。
  • 0