一文搞懂Python上下文管理器

x33g5p2x  于2021-12-30 转载在 Python  
字(1.9k)|赞(0)|评价(0)|浏览(185)

一、什么是上下文管理器

我们在处理文件的时候经常看到下面这样的代码,它即是上下文管理器:

with open('test.txt', encoding='utf-8') as f:
    print(f.readlines())

它的含义是打开当前目录下的test.txt文件并打印它里面的内容,与下面的代码效果是一样的:

f = open('test.txt', encoding='utf-8')
print(f.readlines())
f.close()

对比两种写法能够发现,使用with自动执行了f.close()(关闭文件)的这步操作,能够少写一点代码。

那这样的上下文管理器是怎么实现的,下面为你讲解。

二、如何实现上下文管理器

1. 通过类实现

如果要实现上面open的上下文管理器功能,我们可以通过创建一个类,并添加__enter____exit__方法即可,如下面的代码所示:

class DiyOpen(object):

    def __init__(self, filename, **kwargs):
        self.f = open(filename, **kwargs)

    def __enter__(self):
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        print('关闭文件')
        self.f.close()

with DiyOpen('test.txt', encoding='utf-8') as f:
    print(f.readlines())

输出结果

['第一行\n', '第二行\n', '第三行']
关闭文件

可以看到在我们打印出文件内容后,自动执行了关闭文件的操作。

__enter____exit__的含义是什么,__exit__后面的exc_type, exc_val, exc_tb又是什么意思呢?

1)enter

__enter__相对来说好理解的多,当出现with语句时,它就会被触发,有返回值时,会把返回值赋值给as声明的变量,也就是我们上面的as f中的f

2)exit

__exit__是在with执行完成后自动执行的,他后面的参数含义如下:

  1. exc_type:异常类型
  2. exc_val:异常原因
  3. exc_tb:堆栈追踪信息

当with中执行的代码报错时,除了不继续执行with包含的代码外,还会将报错信息放入上面的三个参数中,例如下面的代码:

class DiyOpen(object):

    def __init__(self, filename, **kwargs):
        self.f = open(filename, **kwargs)

    def __enter__(self):
        return self.f

    def __exit__(self, exc_type, exc_val, exc_tb):
        print(exc_type)
        print(exc_val)
        print(exc_tb)
        self.f.close()

with DiyOpen('test.txt', encoding='utf-8') as f:
    print(f.no())

输出结果

<class 'AttributeError'>
'_io.TextIOWrapper' object has no attribute 'no'
<traceback object at 0x000002A34B834900>

需要注意的是:

  1. 我们可以手动指定__exit__的返回值为True让它不报错。
  2. 没有异常信息时,上面的三个参数值都会为None

2. 通过contextlib实现

Python内置了contextlib这个模块用于实现上下文管理器,它是通过生成器yield实现的,这个模块让我们不必再创建类和__enter__和__exit__了。

通过contextlib实现open功能的代码如下:

from contextlib import contextmanager

@contextmanager
def diy_open(filename, **kwargs):
    f = open(filename, **kwargs)  # __init__
    try:
        yield f  # __enter__
    finally:  # __exit__
        f.close()

with diy_open('test.txt', encoding='utf-8') as f:
    print(f.readlines())

新专栏《从0构建自动化测试平台》 欢迎订阅支持!
平台在线演示地址:http://121.43.43.59/ (帐号:admin 密码:123456)

相关文章