【问题标题】:How to return outer function if any of the inner functions returns如果任何内部函数返回,如何返回外部函数
【发布时间】:2023-02-23 02:11:30
【问题描述】:

请参阅以下示例:

def a(test):
    if test > 1:
        raise Exception("error in 'a'")
    print("nothing happened")

def b(test):
    if test > 1:
        raise Exception("error in 'b'")
    print("nothing happened")

def c(test):
    if test > 1:
        raise Exception("error in 'c'")
    print("nothing happened")

def all():
    try:
        a(1)
    except Exception:
        print("finished due to error")
        return False
    try:
        b(2)
    except Exception:
        print("finished due to error")
        return False
    try:
        c(1)
    except Exception:
        print("finished due to error")
        return False


if __name__ == "__main__":
    all()

输出为:

nothing happened
finished due to error

所以我想要实现的是 all() 在任何内部函数失败时完成,返回 False。

有没有办法像这样编写all()函数,从内部修改内部函数,以便它们将“return False”传递给外部函数?

def all():
    a(1)
    b(2)
    c(1)

(目前的输出是):

Traceback (most recent call last):
  File "/Users/matiaseiletz/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/aaa.py", line 24, in <module>
    all()
  File "/Users/matiaseiletz/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/aaa.py", line 18, in all
    b(2)
  File "/Users/matiaseiletz/Library/Application Support/JetBrains/PyCharmCE2021.2/scratches/aaa.py", line 8, in b
    raise Exception("error in 'b'")
Exception: error in 'b'
nothing happened

目标是获得与第一个输出类似的输出,但没有围绕每个函数的所有 try - except 逻辑。

非常感谢

【问题讨论】:

  • 仅供参考,已经有一个名为all() 的内置函数,您应该为您的函数使用不同的名称。
  • 遍历函数,在循环内放置一个 try-except,在 except 主体中放置一个 return False
  • 不可以。您可以不捕获异常,但不能强制隐式返回。

标签: python python-3.x


【解决方案1】:

你可以重写这个:

    try:
        a(1)
    except Exception:
        print("finished due to error")
        return False
    try:
        b(2)
    except Exception:
        print("finished due to error")
        return False
    try:
        c(1)
    except Exception:
        print("finished due to error")
        return False

简单地说:

    try:
        a(1)
        b(2)
        c(1)
        return True  # assuming you want to do this on a success?
    except Exception:
        print("finished due to error")
        return False

这是 try/except 块要点的重要组成部分——只要没有异常,try 块就会继续,并且引发的第一个异常会立即中断执行并转到匹配的 except(如果有的话) ).没有必要将每一行都包装在自己的try 中,除非您想以不同方式处理每一行的异常。

把它写成一个可重用的函数,你可以这样做:

def try_all(*funcs_and_args) -> bool:
    try:
        for func, *args in funcs_and_args:
            func(*args)
        return True
    except Exception as e:
        print("finished due to error:", e)
        return False

try_all((a, 1), (b, 2), (c, 1))

产生输出:

nothing happened
finished due to error: error in 'b'

你的except 也可以打印类似func.__name__args 的信息,如果这些信息对调试有用的话。

【讨论】:

    【解决方案2】:

    只需在整个函数体周围放置一个try/except

    def my_all():
        try:
            a(1)
            b(2)
            c(1)
        except Exception:
            print("finished due to error")
            return False
        return True
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 2018-08-19
      • 1970-01-01
      相关资源
      最近更新 更多