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 小时前
使用 Google 开源 AI 工具 LangExtract 进行结构化信息抽取
python·google·openai
久笙&1 小时前
对象存储解决方案:MinIO 的架构与代码实战
数据库·python·架构
不甘懦弱2 小时前
阿里云搭建flask服务器
服务器·python·flask
赵英英俊2 小时前
Python day51
人工智能·pytorch·python
律品2 小时前
pytest的前置与后置
开发语言·python·pytest
飞翔的佩奇2 小时前
【完整源码+数据集+部署教程】遥感森林砍伐检测系统源码和数据集:改进yolo11-SWC
python·yolo·计算机视觉·数据集·yolo11·遥感森林砍伐检测
阿汤哥的程序之路3 小时前
Python如何将两个列表转化为一个字典
python
RabbitYao3 小时前
Android 项目 通过 AndroidStringsTool 更新多语言词条
android·python
RabbitYao3 小时前
使用 Gemini 及 Python 更新 Android 多语言 Excel 文件
android·python
天天进步20153 小时前
Python机器学习入门:用scikit-learn构建你的第一个预测模型
python·机器学习·scikit-learn