What's the advantage of using 'with .. as' statement in Python?

好久不见. 提交于 2019-11-27 22:48:17
mg.

In order to be equivalent to the with statement version, the code you wrote should look instead like this:

f = open("hello.txt", "wb")
try:
    f.write("Hello Python!\n")
finally:
    f.close()

While this might seem like syntactic sugar, it ensures that you release resources. Generally the world is more complex than these contrived examples and if you forget a try.. except... or fail to handle an extreme case, you have resource leaks on your hands.

The with statement saves you from those leaks, making it easier to write clean code. For a complete explanation, look at PEP 343, it has plenty of examples.

If f.write throws an exception, f.close() is called when you use with and not called in the second case. Also f has a smaller scope and the code is cleaner when using with.

djc

The former still closes f if an exception occurs during the f.write().

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!