执行代码块如果条件或异常 [英] Execute code block if condition or exception

查看:146
本文介绍了执行代码块如果条件或异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有些例外是习惯Python的核心,如果某个表达式的计算结果为True ,则执行特定代码块是一种干净的方式,引发异常?通过干净,我的意思是一个易于阅读的Pythonic,而不是重复代码块?



例如,而不是:

  try:
如果some_function(data)为None:
report_error('Something happen')
除了SomeException:
report_error('Something occurred')#重复代码

可以将其彻底重写,以便 report_error()不写两次?



(类似的问题:如何在try块中执行相同的代码,在except子句中重复代码,但这是针对特定情况,通过if语句中的简单测试可以避免异常。)

解决方案

是的,这可以做得比较干净,尽管它可以被认为是好的风格是开放的sti。

  def test(expression,exception_list,on_exception):
try:
return expression()
除了exception_list:
return on_exception

如果test(lambda:some_function(data),SomeException,None)是None:
report_error('Something happen')

这来自拒绝的一个想法 PEP 463



lambda到Rescue 呈现相同的想法。


With exceptions being so central to idiomatic Python, is there a clean way to execute a particular code block if an expression evaluates to True or the evaluation of the expression raises an exception? By clean, I mean an easy-to-read, Pythonic, and not repeating the code block?

For example, instead of:

try:
    if some_function(data) is None:
        report_error('Something happened')
except SomeException:
    report_error('Something happened') # repeated code

can this be cleanly rewritten so that report_error() isn't written twice?

(Similar question: How can I execute same code for a condition in try block without repeating code in except clause but this is for a specific case where the exception can be avoided by a simple test within the if statement.)

解决方案

Yes, this can be done relatively cleanly, although whether it can be considered good style is an open question.

def test(expression, exception_list, on_exception):
    try:
        return expression()
    except exception_list:
        return on_exception

if test(lambda: some_function(data), SomeException, None) is None:
    report_error('Something happened')

This comes from an idea in the rejected PEP 463.

lambda to the Rescue presents the same idea.

这篇关于执行代码块如果条件或异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆