What are the real performance advantages of using
with open(__file__, 'r') as f:
instead of using:
open(__file__,'r')
in Python 3 for both writing and reading files?
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.
With the “With” statement, you get better syntax and exceptions handling. “The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks.” In addition, it will automatically close the file. The with statement provides a way for ensuring that a clean-up is always used.
with statement in Python is used in exception handling to make the code cleaner and much more readable. It simplifies the management of common resources like file streams. Observe the following code example on how the use of with statement makes code cleaner.
Using with
means that the file will be closed as soon as you leave the block. This is beneficial because closing a file is something that can easily be forgotten and ties up resources that you no longer need.
What the with statement basically does is take advantage of two new magic keywords on an object: __enter__
and __exit__
to implement automatic cleanup (c++ destructors, .net IDisposable, etc). So what effectively happens is as follows:
file = open(__file__, 'r')
try:
# your code here
finally: file.close()
Feel free to read a bit more about the actual implementation in pep-0343
To answer your question of what performance advantage, there is none from a strict CPU/memory standpoint. Your code won't perform any better, but it will be more robust with less typing and it should be more clear and thus easier to maintain. So in a sense, the performance gain will be measured in man-hours in later maintenance, which as we all should know is the true cost of software, so it will have a great "performance advantage". ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With