I\'m curious if it is considered safe or good practice to depend on python\'s with...as statement. For example when opening a file:
with open(\"myfile\",\"w\") a
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:
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.
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.).
Yes, the with
statement is better way. Since Python 2.5, the file object has been equipped with __enter__()
and __exit__()
methods. The __exit__()
method closes the file object.
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. You need to manually verify that.