Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding the Python 'with' statement

Tags:

python

I'm trying to understand if there is there a difference between these, and what that difference might be.

Option One:

file_obj = open('test.txt', 'r')  with file_obj as in_file:     print in_file.readlines() 

Option Two:

with open('test.txt', 'r') as in_file:     print in_file.readlines() 

I understand that with Option One, the file_obj is in a closed state after the with block.

like image 599
MikeTheReader Avatar asked Sep 03 '15 15:09

MikeTheReader


People also ask

How does the with statement work in Python?

In Python, the with statement replaces a try-catch block with a concise shorthand. More importantly, it ensures closing resources right after processing them. A common example of using the with statement is reading or writing to a file. A function or class that supports the with statement is known as a context manager.

What is the use of with statement?

Thus, with statement helps avoiding bugs and leaks by ensuring that a resource is properly released when the code using the resource is completely executed. The with statement is popularly used with file streams, as shown above and with Locks, sockets, subprocesses and telnets etc.

What is a statement in Python example?

So, in simple words, we can say anything written in Python is a statement. Python statement ends with the token NEWLINE character. It means each line in a Python script is a statement. For example, a = 10 is an assignment statement.

What is the advantage of using with statement in Python?

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.


1 Answers

I don't know why no one has mentioned this yet, because it's fundamental to the way with works. As with many language features in Python, with behind the scenes calls special methods, which are already defined for built-in Python objects and can be overridden by user-defined classes. In with's particular case (and context managers more generally), the methods are __enter__ and __exit__.

Remember that in Python everything is an object -- even literals. This is why you can do things like 'hello'[0]. Thus, it does not matter whether you use the file object directly as returned by open:

with open('filename.txt') as infile:     for line in infile:         print(line) 

or store it first with a different name (for example to break up a long line):

the_file = open('filename' + some_var + '.txt') with the_file as infile:     for line in infile:         print(line) 

Because the end result is that the_file, infile, and the return value of open all point to the same object, and that's what with is calling the __enter__ and __exit__ methods on. The built-in file object's __exit__ method is what closes the file.

like image 52
Two-Bit Alchemist Avatar answered Sep 21 '22 14:09

Two-Bit Alchemist