Python的with语句
参考这里:
In python the
withkeyword is used when working with unmanaged resources (like file streams). It is similar to theusingstatement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' fortry/finallyblocks.
这里说 with 关键字是try/finally的语法糖,用于最终释放资源。
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.
上面解释了一下with语句和try/catch的关系,上面这句话如果发生异常,with语句会先关闭文件,然后异常才会被外层句柄捕获。如果嵌套的块里面有return、continue或者break语句,with语句也会关闭文件。
参考这里,这里讲with的原理其实不是那么简单,with这句语句是有一些规则:
The expression is evaluated and should result in an object called a “context manager”. The context manager must have
__enter__()and__exit__()methods.The context manager’s
__enter__()method is called. The value returned is assigned to VAR. If noas VARclause is present, the value is simply discarded.The code in BLOCK is executed.
If BLOCK raises an exception, the context manager’s
__exit__()method is called with three arguments, the exception details (type, value, traceback, the same values returned bysys.exc_info(), which can also beNoneif no exception occurred). The method’s return value controls whether an exception is re-raised: any false value re-raises the exception, andTruewill result in suppressing it. You’ll only rarely want to suppress the exception, because if you do the author of the code containing the ‘with’ statement will never realize anything went wrong.If BLOCK didn’t raise an exception, the
__exit__()method is still called, but type, value, and traceback are allNone.
上面这段是较高层级的对于实现的解释。
参考:
https://stackoverflow.com/questions/1369526/what-is-the-python-keyword-with-used-for
https://docs.python.org/3/whatsnew/2.6.html#pep-343-the-with-statement
posted on 2019-12-15 17:05 chaiyu2002 阅读(86) 评论(0) 收藏 举报
浙公网安备 33010602011771号