Python from contextlib import contextmanager的使用

1、from contextlib import contextmanager的作用

用装饰器的方式实现上下文管理,这里以为打文件为例

2、用法来源

在学习Kombu队列源码里面:kombu.mixins.ConsumerMixin.py

3、简单的示例

from contextlib import contextmanager

@contextmanager
def open_file():
    try:
        yield open('tasks.py', 'r', encoding='utf-8')
    finally:
        print('读取完成')

if __name__ == '__main__':
    with open_file() as rf:
        print(rf.readline())

4、kombu.mixins.ConsumerMixin.py源码部分

原文地址:https://www.cnblogs.com/ygbh/p/14081856.html