在 Python 2.5 版本之后,出现了一个 with
的语句写法:
with open('openfile', encoding="utf-8") as _file:
read_data = _file.read()
在 Python 官方文档,这样描述:
The
with
statement is used to wrap the execution of a block with methods defined by a context manager (see section With Statement Context Managers). This allows commontry
…except
…finally
usage patterns to be encapsulated for convenient reuse.
with 语句对一段定义在上下文管理器的代码进行包装。这样就能够对传统 try-except-finally
封装起来,更方便使用
通过 with
语句,让代码更容易理解,是 with
语句的作用
在 Python Enhancement Proposals 343 (下称 PEP343) 里面,Python 作者 Guido 描述了一下 with
语句产生的过程,还蛮有意思的
PEP 是提供给社区的设计文档。用来描述一个新特性及其处理过程。PEP 作者用来在社区建立共识并且记录不同意见
在 python 邮件组里面,有个叫 Shannon -jj Behrens 开发者提出了一个 anonymous blocks 的写法:
items.doFoo(
def (a, b) {
return a + b
},
def (c, d) {
return c + d
}
)
在这个写法里面,{}
的用法导致了 Guido 的意见。Guido 在邮件列表中这样说
I think that putting the defs before the call (and giving the anonymous blocks temporary local names) actually makes the code clearer:
def block1(a, b