简体   繁体   English

以...作为声明依赖python是一种好习惯

[英]Is it good practice to depend on python's with…as statement

I'm curious if it is considered safe or good practice to depend on python's with...as statement. 我很好奇是否认为安全或良好的做法依赖于python的...作为声明。 For example when opening a file: 例如,打开文件时:

with open("myfile","w") as myFile:
    #do something

So in this example I neglected to explicitly call myFile.close() however I can assume it was called when python exited the with...as statement by calling the objects __exit__() method. 所以在这个例子中我忽略了显式调用myFile.close()但是我可以假设当python通过调用对象__exit__()方法退出with...as语句时调用它。 Is it good practice/safe to depend upon this or would it be better to always explicitly call file.close() 依赖于此是好的做法/安全还是总是明确调用file.close()会更好

This is what context managers are for , to rely on them to close the file for you. 这是什么情况下管理者 ,依靠他们关闭文件给你。 Context managers are called even if there was an exception. 即使存在异常,也会调用上下文管理器。

The alternative is to use an finally block instead: 另一种方法是使用finally块代替:

myFile = open("myfile","w")
try:
    # do something with myFile
finally:
    myFile.close()

but because the block inside of the try: might be long, by the time you get to the finally statement you have forgotten what you were setting this up for. 但是因为try:里面的块可能很长,当你到达finally语句时,你已经忘记了你为此设置的内容。

Context managers are more powerful still. 上下文管理器仍然更强大。 Because the __exit__ method is informed of any exceptions, they can act as exception handlers as well (ignore the exception, raise another, etc.). 因为__exit__方法被告知任何异常,所以它们也可以充当异常处理程序(忽略异常,引发异常等)。

Yes, the with statement is better way. 是的, with声明是更好的方法。 Since Python 2.5, the file object has been equipped with __enter__() and __exit__() methods. 因为Python 2.5,文件对象已经配备了__enter__()__exit__()方法。 The __exit__() method closes the file object. __exit__()方法关闭文件对象。

Python guarantees that it will call the __exit__() method, but there is not guarantee that the __exit__() method will close the resource, especially with 3rd party code. Python保证它将调用__exit__()方法,但不能保证__exit__()方法将关闭资源,尤其是第三方代码。 You need to manually verify that. 您需要手动验证。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM