Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python exception handling in list comprehension

I have a Python function called plot_pdf(f) that might throw an error. I use a list comprehension to iterate over a list of files on this function:

[plot_pdf(f) for f in file_list]

I want to use try-except block to skip any possible errors during the iteration loop and continue with the next file. So is the following code correct way to do the exception handling in Python list comprehension?

try:
    [plot_pdf(f) for f in file_list]  # using list comprehensions
except:
    print ("Exception: ", sys.exc_info()[0])
    continue

Will the above code terminate the current iteration and go to the next iteration? If I can't use list comprehension to catch errors during iteration, then I have to use the normal for loop:

for f in file_list:
    try:
        plot_pdf(f)
    except:
        print("Exception: ", sys.exc_info()[0])
        continue

I want to know if I can use try-except to do exception handling in list comprehension.

like image 406
tonga Avatar asked May 17 '13 14:05

tonga


People also ask

How do you handle exceptions in list comprehension?

There is no built-in function in Python that lets you handle or ignore an exception, so it's not possible to handle all exceptions in a list comprehension because a list comprehension contains one or more expressions; only statements can catch/ignore/handle exceptions.

Can we use append in list comprehension?

Using append() to tell Python that each new element should be added to the end is also unnecessary; we don't need to use append() in list comprehension. Instead, we are just defining the variable highest_paid_actors_birthyear and assigning the list comprehension result to that variable.

Can you do list comprehension in Python?

List comprehension in Python is an easy and compact syntax for creating a list from a string or another list. It is a very concise way to create a new list by performing an operation on each item in the existing list. List comprehension is considerably faster than processing a list using the for loop.

Can you nest list comprehensions?

As it turns out, you can nest list comprehensions within another list comprehension to further reduce your code and make it easier to read still. As a matter of fact, there's no limit to the number of comprehensions you can nest within each other, which makes it possible to write very complex code in a single line.


2 Answers

try:
    [plot_pdf(f) for f in file_list]  # using list comprehensions
except:
    print ("Exception: ", sys.exc_info()[0])
    continue

If plot_pdf(f) throws an error during execution of comprehension, then, it is caught in the except clause, other items in comprehension won't be evaluated.

It is not possible to handle exceptions in a list comprehension, for a list comprehension is an expression containing other expression, nothing more (i.e. no statements, and only statements can catch/ignore/handle exceptions).

Function calls are expression, and the function bodies can include all the statements you want, so delegating the evaluation of the exception-prone sub-expression to a function, as you've noticed, is one feasible workaround (others, when feasible, are checks on values that might provoke exceptions, as also suggested in other answers).

More here.

like image 167
kiriloff Avatar answered Sep 21 '22 02:09

kiriloff


You're stuck with your for loop unless you handle the error inside plot_pdf or a wrapper.

def catch_plot_pdf(f):
    try:
        return plot_pdf(f)
    except:
        print("Exception: ", sys.exc_info()[0])

[catch_plot_pdf(f) for f in file_list]
like image 32
Daenyth Avatar answered Sep 22 '22 02:09

Daenyth