`
54yuri
  • 浏览: 28234 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【转帖】Understanding Python's "with" statement

阅读更多
Judging from comp.lang.python and other forums, Python 2.5’s new with statement seems to be a bit confusing even for experienced Python programmers.

As most other things in Python, the with statement is actually very simple, once you understand the problem it’s trying to solve. Consider this piece of code:

    set things up
    try:
        do something
    finally:
        tear things down


Here, “set things up” could be opening a file, or acquiring some sort of external resource, and “tear things down” would then be closing the file, or releasing or removing the resource. The try-finally construct guarantees that the “tear things down” part is always executed, even if the code that does the work doesn’t finish.

If you do this a lot, it would be quite convenient if you could put the “set things up” and “tear things down” code in a library function, to make it easy to reuse. You can of course do something like

    def controlled_execution(callback):
        set things up
        try:
            callback(thing)
        finally:
            tear things down

    def my_function(thing):
        do something

    controlled_execution(my_function)


But that’s a bit verbose, especially if you need to modify local variables. Another approach is to use a one-shot generator, and use the for-in statement to “wrap” the code:

    def controlled_execution():
        set things up
        try:
            yield thing
        finally:
            tear things down

    for thing in controlled_execution():
        do something with thing


But yield isn’t even allowed inside a try-finally in 2.4 and earlier. And while that could be fixed (and it has been fixed in 2.5), it’s still a bit weird to use a loop construct when you know that you only want to execute something once.

So after contemplating a number of alternatives, GvR and the python-dev team finally came up with a generalization of the latter, using an object instead of a generator to control the behaviour of an external piece of code:

    class controlled_execution:
        def __enter__(self):
            set things up
            return thing
        def __exit__(self, type, value, traceback):
            tear things down

    with controlled_execution() as thing:
         some code


Now, when the “with” statement is executed, Python evaluates the expression, calls the __enter__ method on the resulting value (which is called a “context guard”), and assigns whatever __enter__ returns to the variable given by as. Python will then execute the code body, and no matter what happens in that code, call the guard object’s __exit__ method.

As an extra bonus, the __exit__ method can look at the exception, if any, and suppress it or act on it as necessary. To suppress the exception, just return a true value. For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through:

    def __exit__(self, type, value, traceback):
        return isinstance(value, TypeError)


In Python 2.5, the file object has been equipped with __enter__ and __exit__ methods; the former simply returns the file object itself, and the latter closes the file:

    >>> f = open("x.txt")
    >>> f
    <open file 'x.txt', mode 'r' at 0x00AE82F0>
    >>> f.__enter__()
    <open file 'x.txt', mode 'r' at 0x00AE82F0>
    >>> f.read(1)
    'X'
    >>> f.__exit__(None, None, None)
    >>> f.read(1)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    ValueError: I/O operation on closed file

so to open a file, process its contents, and make sure to close it, you can simply do:

with open("x.txt") as f:
    data = f.read()
    do something with data

This wasn’t very difficult, was it?

[comment on/vote for this article]


Fredrik Lundh | October 2006 | Originally posted to online.effbot.org
http://effbot.org/zone/python-with-statement.htm
分享到:
评论

相关推荐

    mayaPython

    Maya Programming with Python Cookbook MayaPythonForGamesAndFilm Prentice.Hall.Rapid.GUI.Programming.with.Python.and.Qt.Oct.2007 Robert Galanakis - Practical Maya Programming with Python - 2014

    论坛转帖工具.rar

    标题中的“论坛转帖工具.rar”表明这是一个用于在论坛之间转移帖子的软件工具,通常用于帮助用户方便地将一个论坛的帖子内容复制到另一个论坛,可能是为了分享信息、讨论或保存重要的帖子。这类工具可能包括自动抓取...

    UBB论坛转帖圣手.exe

    UBB论坛转帖圣手.exeUBB论坛转帖圣手.exe

    贴吧转帖工具

    【贴吧转帖工具】是一种专为百度贴吧用户设计的便捷工具,主要用于提高用户在贴吧中的互动效率。通过这款工具,用户可以实现一键转帖和一键8经验签到的功能,极大地简化了传统操作流程,节省了用户的时间,提升了...

    编辑人员转帖去水印工具

    本篇文章将详细探讨“编辑人员转帖去水印工具”,并介绍如何使用名为Teorex Inpaint的1.0.0.2版本的软件来实现这一目标。 首先,我们要理解什么是水印。水印通常是指在图像或视频中添加的半透明标记,它可以是文字...

    [转帖]世界编程大赛第一名写的程序

    Python则以其简洁的语法和丰富的库支持,在数据处理和算法原型设计方面表现出色。 5. **团队协作**:在团队赛中,有效的沟通和分工合作是成功的关键。团队成员应根据各自的优势分配任务,如一人负责算法设计,另一...

    discuz X2转帖工具、采集工具

    X2转帖工具、采集工具”是针对这个平台设计的辅助软件,主要用于帮助论坛管理员或用户批量发布帖子和采集内容,提高论坛内容更新的效率。 一、批量发帖功能 1. 自动化发布:此工具可以自动化地创建和发布帖子,...

    转帖工具ConvertX fordiscuz7.1/7.2 修改增强版.rar

    1.修改自Convert X转帖工具 2.新增批量替换关键词(原来是单个词语替换,可以利用这个功能删除一些网站的防转帖代码) 3.批量随机新增文字(新增内容可自定义,从而实现伪原创) 4.cookie记录替换和新增关键词(避免每次...

    转帖工具插件 for PHPwind 7.5 正式版.rar

    "转帖工具插件 for PHPwind 7.5 正式版" 是专门为 PHPwind 7.5 版本设计的一个功能插件,旨在提供便捷的帖子转移功能,帮助管理员或者用户将内容从一个地方轻松移动到另一个地方,而无需直接编辑论坛的原始文件。...

    一键转帖功能插件 for 帝国CMS 6.0 GBK utf8 V1.0.rar

    《一键转帖功能插件 for 帝国CMS 6.0 GBK utf8 V1.0》 本文将深入探讨“一键转帖功能插件”在帝国CMS 6.0系统中的应用与实现,该插件适用于GBK及UTF-8编码环境,旨在提升网站内容的分享与传播效率。我们将从安装...

    转帖图片提取工具 v1.0.zip

    转帖图片提取工具可以对论坛图片附件信息进行清除,只保留图片代码,操作很简单,推荐有需要转帖图片工具的朋友下载 转帖图片提取工具使用方法: 将IP138上处理过的东西复制到上方的编辑框内,点击只要图片,下面...

    Html2UBBMaxcj_Softii论坛专用转帖工具

    HTML2UBBMaxcj 是一款专为Softii论坛设计的转帖工具,它主要用于将HTML格式的帖子内容转换成UBB代码,以便在论坛中更好地显示和分享。UBB(Universal BBCode)是一种轻量级的标记语言,常用于网络论坛,与HTML类似,...

    一键转帖功能插件 for 帝国CMS v1.0.rar

    "一键转帖功能插件 for 帝国CMS v1.0.rar" 是一个专为帝国CMS设计的扩展工具,其主要目标是简化用户在网站上分享内容的过程,提高用户体验。这个插件允许用户轻松地将网站上的文章或信息复制并转发到其他平台,如...

    超级无敌转帖手

    看到论坛里帖子由精美的图片想转过来,或者批量提取地址时很好用

    人人网 qq 51 优酷 分享或者转帖

    转发至人人网" charset="400-03-7" id="s_renren" href="http://share.renren.com/share/buttonshare.do?link=http://www.ttup.me" target="_blank"&gt;&lt;img src="images/分享到人人网.jpg" /&gt; 分数可能有点高,这个和...

    高三政治教学总结(转帖)教学工作总结.doc

    高三政治教学总结(转帖)教学工作总结.doc

    J2ME全方位开发讲解基础汇总[转帖]

    J2ME全方位开发讲解基础汇总[转帖] 一、J2ME中需要的Java基础知识 现在有大部分人,都是从零开始学J2ME的,学习J2ME的时候,总是从Java基础开始学习,而且现在讲Java基础的书籍中都是以J2SE来讲基础,这就给学习造成...

    轻松转帖之突破网页复制限制宣贯.pdf

    UBB转帖王是一种插件,它能够帮助用户快速去除复制下来的网页内容中的无用空格、文字干扰码、水印和空行等,优化复制内容,便于分享和阅读。 【其他浏览器解决方案】 除了火狐,其他浏览器如搜狗、遨游和世界之窗也...

    H42131-转帖《关于用净值计算法计算收益》.doc

    H42131-转帖《关于用净值计算法计算收益》.doc

Global site tag (gtag.js) - Google Analytics