简体   繁体   English

列表推导中的Python异常处理

[英]Python exception handling in list comprehension

I have a Python function called plot_pdf(f) that might throw an error. 我有一个名为plot_pdf(f)的Python函数可能会抛出错误。 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. 我想使用try-except块在迭代循环期间跳过任何可能的错误并继续下一个文件。 So is the following code correct way to do the exception handling in Python list comprehension? 以下代码在Python列表理解中进行异常处理的正确方法是什么?

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循环:

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. 我想知道我是否可以使用try-except在列表理解中进行异常处理。

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. 如果plot_pdf(f)在执行理解期间抛出错误,那么,它将被捕获在except子句中,其他理解项将不会被评估。

It is not possible to handle exceptions in a list comprehension, for a list comprehension is an expression containing other expression, nothing more (ie 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. 更多这里。

You're stuck with your for loop unless you handle the error inside plot_pdf or a wrapper. 除非你在plot_pdf或包装器中处理错误,否则你会遇到for循环。

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]

You could create a catch object 您可以创建一个catch对象

def catch(error, default, function, *args, **kwargs):
    try: return function(*args, **kwargs)
    except error: return default

Then you can do 那你可以做

# using None as default value
result (catch(Exception, None, plot_pdf, f) for f in file_list)  

And then you can do what you want with the result: 然后你可以用你的结果做你想做的事情:

result = list(result)  # turn it into a list
# or
result = [n for n in result if n is not None]  # filter out the Nones

Unfortunately this will not be even remotely C speed, see my question here 不幸的是,这甚至不是远程C速度, 请看我的问题

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM