The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.
The with statement is a control-flow structure whose basic structure is:
with expression [as variable]:
with-block
The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).
It’s handy when you have two related operations which you’d like to
execute as a pair, with a block of code in between. The classic
example is opening a file, manipulating the file, then
closing it:
with open('output.txt', 'w') as f:
f.write('Hi there!')
The above with statement will automatically close the file after the
nested block of code. (Continue reading to see exactly how the close
occurs.) The advantage of using a with statement is that it is
guaranteed to close the file no matter how the nested block exits. If
an exception occurs before the end of the block, it will close the
file before the exception is caught by an outer exception handler. If
the nested block were to contain a return statement, or a continue or
break statement, the with statement would automatically close the file
in those cases, too.
在python中,
with
关键字用于处理非托管资源(如文件流)。它类似于VB.NET和C中的using
语句。它允许您确保在使用资源的代码完成运行时“清理”该资源,即使抛出异常。它为try/finally
块提供“语法糖”。来自Python Docs:
更新根据Scott Wisniewski的评论修复了VB标注。我确实把
with
和using
搞混了。Explanation from the Preshing on Programming blog:
相关问题 更多 >
编程相关推荐