Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, if I return inside a "with" block, will the file still close?

Consider the following:

with open(path, mode) as f:     return [line for line in f if condition] 

Will the file be closed properly, or does using return somehow bypass the context manager?

like image 323
Lightbreeze Avatar asked Mar 27 '12 07:03

Lightbreeze


People also ask

Does With close the file?

No. It will open the file, do its job then close the file.

Does Python stop after return?

In Python, however, main is called explicitly within the program code, so the return statement itself does not exit the program. Show activity on this post. In fact, the return statement will end your function. So your print won't be executed.

What happens when you return in Python?

A return statement is used to end the execution of the function call and “returns” the result (value of the expression following the return keyword) to the caller. The statements after the return statements are not executed.

How do you make sure a file is closed after using it Python?

You can use the with statement to open the file, which will ensure that the file is closed. See http://www.python.org/dev/peps/pep-0343/ for more details.


2 Answers

Yes, it acts like the finally block after a try block, i.e. it always executes (unless the python process terminates in an unusual way of course).

It is also mentioned in one of the examples of PEP-343 which is the specification for the with statement:

with locked(myLock):     # Code here executes with myLock held.  The lock is     # guaranteed to be released when the block is left (even     # if via return or by an uncaught exception). 

Something worth mentioning is however, that you cannot easily catch exceptions thrown by the open() call without putting the whole with block inside a try..except block which is usually not what one wants.

like image 192
ThiefMaster Avatar answered Oct 16 '22 08:10

ThiefMaster


Yes.

def example(path, mode):     with open(path, mode) as f:         return [line for line in f if condition] 

..is pretty much equivalent to:

def example(path, mode):     f = open(path, mode)      try:         return [line for line in f if condition]     finally:         f.close() 

More accurately, the __exit__ method in a context manager is always called when exiting the block (regardless of exceptions, returns etc). The file object's __exit__ method just calls f.close() (e.g here in CPython)

like image 27
dbr Avatar answered Oct 16 '22 09:10

dbr