Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using python "with" statement with try-except block

Is this the right way to use the python "with" statement in combination with a try-except block?:

try:     with open("file", "r") as f:         line = f.readline() except IOError:     <whatever> 

If it is, then considering the old way of doing things:

try:     f = open("file", "r")     line = f.readline() except IOError:     <whatever> finally:     f.close() 

Is the primary benefit of the "with" statement here that we can get rid of three lines of code? It doesn't seem that compelling to me for this use case (though I understand that the "with" statement has other uses).

EDIT: Is the functionality of the above two blocks of code identical?

EDIT2: The first few answers talk generally about the benefits of using "with", but those seem of marginal benefit here. We've all been (or should have been) explicitly calling f.close() for years. I suppose one benefit is that sloppy coders will benefit from using "with".

like image 962
gaefan Avatar asked Sep 04 '10 11:09

gaefan


People also ask

Does With statement support exception handling?

What do you mean "enclosing 'with' in a try/except statement doesn't work else: exception is not raised"? A with statement doesn't magically break a surrounding try... except statement. Interestingly, Java's try-with-resources statement does support exactly this use case you want.

When we use try and except block in Python?

The try block lets you test a block of code for errors. The except block lets you handle the error. The else block lets you execute code when there is no error.

How do you use try except statements in Python?

The try statement works as follows. First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished. If an exception occurs during execution of the try clause, the rest of the clause is skipped.

Can you have a try except within a try except Python?

We can have nested try-except blocks in Python. In this case, if an exception is raised in the nested try block, the nested except block is used to handle it. In case the nested except is not able to handle it, the outer except blocks are used to handle the exception.


1 Answers

  1. The two code blocks you gave are not equivalent
  2. The code you described as old way of doing things has a serious bug: in case opening the file fails you will get a second exception in the finally clause because f is not bound.

The equivalent old style code would be:

try:     f = open("file", "r")     try:         line = f.readline()     finally:         f.close() except IOError:     <whatever> 

As you can see, the with statement can make things less error prone. In newer versions of Python (2.7, 3.1), you can also combine multiple expressions in one with statement. For example:

with open("input", "r") as inp, open("output", "w") as out:     out.write(inp.read()) 

Besides that, I personally regard it as bad habit to catch any exception as early as possible. This is not the purpose of exceptions. If the IO function that can fail is part of a more complicated operation, in most cases the IOError should abort the whole operation and so be handled at an outer level. Using with statements, you can get rid of all these try...finally statements at inner levels.

like image 58
Bernd Petersohn Avatar answered Sep 30 '22 19:09

Bernd Petersohn