Python停止当前缩进级别的执行

2024-06-02 05:10:59 发布

您现在位置:Python中文网/ 问答频道 /正文

有没有办法停止当前缩进级别的执行? 我正在寻找一种方法来打破类似于循环中的break语句的块

if some_state:
    if bool1:
        <jump to some-final-code> # Looking for this operator
    <some code>
    if bool2:
        <jump to some-final-code> # Looking for this operator
    <moa code>
elif some_other_state:
    <some_other_conditions_with_equally_possible_jumps>
<some_final_code>

我知道有很多方法可以以可读的方式解决这个问题。让我们假设整个块的代码在语义上是相关的,不应该用不同的方法分开。引发异常会增加大量代码行和另一种不必要的不理解程度


Tags: to方法代码forifcodesomethis
2条回答

将行为封装到函数中如何?然后可以使用return结束该函数的执行

def myFunction():
    if some_state:
        if bool1:
            return
        <some code>
        if bool2:
            return
        <moa code>
    elif some_other_state:
        <some_other_conditions_with_equally_possible_jumps>

myFunction()
<some_final_code>

您始终可以反转条件,如果您不介意更多缩进级别,则会产生相同的效果:

if some_state:
    if not bool1:
        <some code>
        if not bool2:
            <moa code>
elif some_other_state:
    <some_other_conditions_with_equally_possible_jumps>
<some_final_code>

或者,异常根本不会添加很多行代码:

class GotoCleanup(Exception):
    pass

... whatever other code you have ...

try:
    if some_state:
        if bool1:
            raise GotoCleanup
        <some code>
        if bool2:
            raise GotoCleanup
        <moa code>
    elif some_other_state:
        <some_other_conditions_with_equally_possible_jumps>
finally:
    <some_final_code>

如果要确保只捕获特定的异常,则必须添加两行额外的代码:

try:
    if some_state:
        if bool1:
            raise GotoCleanup
        <some code>
        if bool2:
            raise GotoCleanup
        <moa code>
    elif some_other_state:
        <some_other_conditions_with_equally_possible_jumps>
except GotoCleanup:
    pass
finally:
    <some_final_code>

这将允许其他异常像往常一样传播,并将被视为最佳实践,而不是吞并所有异常

相关问题 更多 >