contextmanager

  1. contextmanager 来自 contextlib 包,通常使用时要进行导入:
    from contextlib import contextmanager
    

  1. contextmanager 作为上下文管理器,主要的作用就是在执行某些逻辑之前,做一些预备工作;执行完逻辑代码之后,做一些收尾和善后 工作。

  1. 首先我们自己实现一个上下文管理器类,用于讲述一下基础原理。

    # -*- coding:utf-8 -*-
    class MyNewClass(object):
        #执行with语句时,先执行 __enter__方法,并将返回值复制给 with 后的变量,比如new_class
        def __enter__(self):
            print("Before exect my_function.")
            return self
    
        # with语句执行完成后,执行 __exit__ 方法,进行收尾、善后(异常处理)等工作,注意*args接收三个参数(exc_type, exc_val, exc_tb)
        # exc_type :若无异常则为 None; 若有异常则为异常类型。
        # exc_val :若无异常则为 None, 若有异常则为异常信息描述。
        # exc_tb :若无异常则为 None, 若有异常则为异常详细追溯信息(TraceBack)。
        def __exit__(self, *args):
            print("After exect my_function.")
    
        def my_function(self):
            print("Exect my_function.")
    
    
    with MyNewClass() as new_class:
        new_class.my_function()
        x = 1/0
    

无异常args内容:


有异常args内容:


  1. 了解了3之后,我们可以通过 contextmanager 上下文管理器来轻松实现。

    # # -*- coding:utf-8 -*-
    from contextlib import contextmanager
    
    
    @contextmanager
    def test_new_contextmanager():
        print("Before exect my_function.")  # yield前内容等同于__enter__
        yield  # 需要执行的方法比如后面的 print("After exect my_function.")
        print("Exect my_function.")  # yield前内容等同于__enter__
    
    
    with test_new_contextmanager() as new_contextmanager:
        print("After exect my_function.")
        1/0
    

无异常:


有异常:




通过上述说明,可以简要的理解contextmanager存在的意义和用法。
更多相关说明,请参阅:contextlib-contextmanager

更多推荐

Python | 基础 | contextmanager