Python中with管理上下文

上下文管理器

上下文管理器本质就是能够支持with操作。

任何实现了**enter() 和 exit()**方法的对象都可称之为上下文管理器,上下文管理器对象可以使用 with 关键字。显然,文件(file)对象也实现了上下文管理器协议。

实现上下文管理器的另外方式

Python 还提供了一个contextmanager 的装饰器 ,更进一步简化了上下文管理器的实现方式。通过 yield 将函数分割成两部分,**yield 之前的语句在 enter 方法中执行,yield 之后的语句在 exit 方法中执行。**紧跟在 yield 后面的值是函数的返回值。

contextmanager装饰器的底层实现就是将yield之前的方法传入到__enter__方法中,将yield之后的方法传入到__exit__方法中

使用contextmanager装饰器需要导入模块

复制代码
from contextlib import contextmanager

使用__enter__和__exit__实现一个上下文管理器

读取同级目录下的hello文件的内容

复制代码
class my_open(object):
    def __init__(self, file_name, file_open_tyope):
        self.file_name = file_name
        self.file_open_type = file_open_tyope

    # 创建上文方法
    def __enter__(self):
        print("进入上文方法")
        self.file = open(self.file_name, self.file_open_type)
        return self.file

    # 创建下文方法
    def __exit__(self, exc_type, exc_val, exc_tb):
        print("进入下文方法")
        self.file.close()


def main():
    with my_open("hello", 'r') as file:
        result = file.read()
        print(result)


if __name__ == '__main__':
    main()

"""
进入上文方法
hello python
进入下文方法
"""

使用装饰器contextmanager实现一个上下文管理器

读取同级目录下的hello文件的内容

复制代码
from contextlib import contextmanager


@contextmanager
def my_open(file_name, file_open_type):
    # 进入上文操作
    print("进入上文")
    file = open(file_name, file_open_type)
    
    # 返回file,进行操作
    yield file
    
    # 进入下文操作
    print("进入下文")
    file.close()


if __name__ == '__main__':
    with my_open("hello", "r") as file:
        result = file.read()
        print(result)
"""
进入上文
hello python
进入下文
"""

总结

Python 提供了 with 语法用于简化资源操作的后续清除操作,实现原理建立在上下文管理器协议(实现__enter__和__exit__)之上

with使用代码中如果在打开过程中发生异常,需要使用try-except进行捕获

Python 还提供了一个 contextmanager 装饰器,更进一步简化上下管理器的实现方式。

相关推荐
数据智能老司机1 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机1 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机1 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i1 小时前
drf初步梳理
python·django
每日AI新事件1 小时前
python的异步函数
python
这里有鱼汤2 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook11 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室12 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三13 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试
用户25191624271117 小时前
Python之语言特点
python