详解python with 上下文管理器


Posted in Python onSeptember 02, 2020

作为一个 Java 为母语的程序员来讲,学习起其他新的语言就难免任何事都与 Java 进行横向对比。Java 7 引入了能省去许多重复代码的 try-with-resources 特性,不用每回 try/finally 来释放资源(不便之处有局部变量必须声明在 try 之前,finally 里还要嵌套 try/catch 来处理异常)。比如下面的 Java 代码

try(InputStream inputStream = new FileInputStream("abc.txt")) {
  System.out.println(inputStream.read());
} catch (Exception ex) {
}

它相应的不使用 try-with-resources 语法的代码就是

InputStream inputStream = null;
try {
  inputStream = new FileInputStream("abc.txt");
} catch (Exception ex) {
} finally {
  if(inputStream != null) {
    try {
      inputStream.close();
    } catch (Exception ex) {
    }
  }
}

类似的 Python 也有自己的 try-with-resources 写法,就是 with 关键字,它的概念叫做上下文管理器(Context Manager)。

with 关键字的使用

with open('some_file', 'w') as opened_file:
  opened_file.write('Hola!')

以上的代码相当于

opened_file = open('some_file', 'w')
try:
  opened_file.write('Hola!')
finally:
  opened_file.close()

也就是 with 关键字打开的资源会在 with 语句块结束后自动调用相应的方法自动释放(无论 with 中操作是否有异常)。

with 用起来是很方便的,但是什么样的资源可以用 with 关键字?Python 是怎么知道要调用哪个方法来关闭资源的?进而如何实现自己的支持上下文管理器的 Python 类。

再次回顾 Java 的 try-with-resources 语法,try(...) 括号支持的类必须是实现了 AutoCloseable 接口,它的接口方法是

public void close() throws IOException

也就是 Java 的 try-with-resources 语法会自动调用以上方法来释放资源,要实现可被自动释放的 Java 就只须遵照这一规则就行。

而在 Python 中,能被 with 的类有两种实现方式

实现基本方法以支持上下文管理器的类

一个 Python 类要能被用于 with 上下文,必须实现至少 __enter__ __exit__ 方法。这两个方法的意思好理解,一个是创建资源后,后者是退出 with 语句块后。请看下面的例子

class File(object):
  def __init__(self, file_name, method):
    self.file_obj = open(file_name, method)
 
  def __enter__(self):
    print("---enter")
    return self.file_obj
 
  def __exit__(self, type, value, traceback):
    print("---exit")
    self.file_obj.close()
 
 
with File('data.txt', 'r') as data_file:
  print(data_file.read())

假设 data.txt 文件中的内容是

hello
world

那么以上程序执行后的输出就是

--enter
hello
world
---exit

  1. __enter__ 返回的值作为 with ... as data_file 中的 data_file 变量的值,如果 __enter__ 没有返回,data_file 得到的就是 NoneType object 了。
  2. __exit__ 可利用来释放资源
  3. 没有 __enter__ 方法试图用 with 的写法执行时会得到 AttributeErro: __enter__ 异常
  4. 同样,没有 __exit__ 方法试图用 with 的写法执行时会得到 AttributeErro: __exit__ 异常
  5. __exit__ 有其他额外的三个参数,可获得资源的值,以及能处理 with 块中执行出现异常的情况
  6. __exit__ 的返回值也有用途,如果它返回 True 则出现的异常不再向外传播,其他值的话直接向外抛

利用生成器(Generator) 和装饰器创建支持上下文管理器的方法

此种方式比较简单,不过逻辑控制上没有这么强。

from contextlib import contextmanager
 
@contextmanager
def open_file(name, method):
  f = open(name, method)
  yield f
  f.close()

使用 f 的执行代码将被放置在 yield f 所处的位置,with 使用以上方法。yield 后的 f 变量将是 with...as 后的变量值

with open_file('some_file', 'w') as file_object:
  file_object.write('hola!')

这里也要注意异常处理的情况,比如把上面代码打开文件的模式换作 r, 仍然试图去写文件,这样在 open_file 方法的 yield f 位置将产生异常,会造成 f.close() 得不到执行,不能正确释放该资源。

欲更具防御性,前面的 yield f 可以扩展也如下的形式

try:
  yield f
except Exception as ex:
  pass #处理异常,或继续向外抛
finally:
  f.close()

@contextmanager 装饰器内部也是封装为一个实现了 __enter__ __exit__ 方法的对象。

参考链接:Context Managers

以上就是详解python with 上下文管理器的详细内容,更多关于python with 上下文管理器的资料请关注三水点靠木其它相关文章!

Python 相关文章推荐
python局部赋值的规则
Mar 07 Python
python获取网页状态码示例
Mar 30 Python
Python函数可变参数定义及其参数传递方式实例详解
May 25 Python
在Django的URLconf中使用命名组的方法
Jul 18 Python
获取python的list中含有重复值的index方法
Jun 27 Python
Python爬虫框架Scrapy基本用法入门教程
Jul 26 Python
Python实现的对本地host127.0.0.1主机进行扫描端口功能示例
Feb 15 Python
django处理select下拉表单实例(从model到前端到post到form)
Mar 13 Python
python框架flask入门之环境搭建及开启调试
Jun 07 Python
python中执行smtplib失败的处理方法
Jul 01 Python
Python单元测试及unittest框架用法实例解析
Jul 09 Python
python如何在word中存储本地图片
Apr 07 Python
Python 的 __str__ 和 __repr__ 方法对比
Sep 02 #Python
Python datetime 如何处理时区信息
Sep 02 #Python
浅析python中的del用法
Sep 02 #Python
浅析NumPy 切片和索引
Sep 02 #Python
详解Python 函数参数的拆解
Sep 02 #Python
Python 常用日期处理 -- calendar 与 dateutil 模块的使用
Sep 02 #Python
python 常用日期处理-- datetime 模块的使用
Sep 02 #Python
You might like
生成php程序的php代码
2008/04/07 PHP
php include,include_once,require,require_once
2008/09/05 PHP
php array的学习笔记
2012/05/16 PHP
php实现的获取网站备案信息查询代码(360)
2013/09/23 PHP
php判断类是否存在函数class_exists用法分析
2014/11/14 PHP
Laravel基础_关于view共享数据的示例讲解
2019/10/14 PHP
TP5多入口设置实例讲解
2020/12/15 PHP
用htc组件制作windows选项卡
2007/01/13 Javascript
jquery keypress,keyup,onpropertychange键盘事件
2010/06/25 Javascript
一款基jquery超炫的动画导航菜单可响应单击事件
2014/11/02 Javascript
node.js中的fs.unlinkSync方法使用说明
2014/12/15 Javascript
jquery实现可拖拽弹出层特效
2015/01/04 Javascript
Flash图片上传组件 swfupload使用指南
2015/03/14 Javascript
jQuery easyui的validatebox校验规则扩展及easyui校验框validatebox用法
2016/01/18 Javascript
微信小程序 免费SSL证书https、TLS版本问题的解决办法
2016/12/14 Javascript
快速解决vue-cli在ie9+中无效的问题
2018/09/04 Javascript
Vue程序化的事件监听器(实例方案详解)
2020/01/07 Javascript
Vue中computed及watch区别实例解析
2020/08/01 Javascript
关于Python 3中print函数的换行详解
2017/08/08 Python
PyQt5 实现给窗口设置背景图片的方法
2019/06/13 Python
python使用socket 先读取长度,在读取报文内容示例
2019/09/26 Python
详解Python可视化神器Yellowbrick使用
2019/11/11 Python
python通过链接抓取网站详解
2019/11/20 Python
Python变量、数据类型、数据类型转换相关函数用法实例详解
2020/01/09 Python
Django基于客户端下载文件实现方法
2020/04/21 Python
python BeautifulSoup库的安装与使用
2020/12/17 Python
中粮集团旗下食品网上购物网站:我买网
2016/09/22 全球购物
洛佩桑酒店官方网站:Lopesan Hotels
2019/04/15 全球购物
策划创业计划书
2014/02/06 职场文书
工程主管竞聘书
2015/09/15 职场文书
青年干部培训班学习心得体会
2016/01/06 职场文书
幼儿教师师德培训心得体会
2016/01/09 职场文书
Nginx 502 Bad Gateway错误原因及解决方案
2021/03/31 Servers
php远程请求CURL案例(爬虫、保存登录状态)
2021/04/01 PHP
golang判断key是否在map中的代码
2021/04/24 Golang
嵌入式Redis服务器在Spring Boot测试中的使用教程
2021/07/21 Redis