'Finally' equivalent for If/Elif statement

2020-06-07 11:20发布

Does Python have a finally equivalent for its if/else statements, similar to its try/except/finally statements? Something that would allow us to simplify this:

 if condition1:
      do stuff
      clean up
 elif condition2:
      do stuff
      clean up
 elif condition3:
      do stuff
      clean up
 ...
 ...

to this:

 if condition1:
      do stuff
 elif condition2:
      do stuff
 elif condition3:
      do stuff
 ...
 ...
 finally:
      clean up

Where finally would only be called only after a condition was met and its 'do stuff' run? Conversely, if no condition was met, the finally code would not be run.

I hate to spout blasphemy, but the best way I can describe it is there being a GOTO statement at the end of each block of 'do stuff' that led to finally.

Essentially, it works as the opposite of an else statement. While else is only run if no other conditions are met, this would be ran ONLY IF another condition was met.

8条回答
倾城 Initia
2楼-- · 2020-06-07 12:01

The answer of mhlester has repetitive code, an improved version might be as follows:

class NoCleanUp(Exception):
    pass

try:
    if condition1:
        do stuff
    elif condition2:
        do stuff
    else:
        raise NoCleanUp
except NoCleanUp:
    pass
else:
    cleanup
查看更多
做个烂人
3楼-- · 2020-06-07 12:03

Another suggestion, which might suit you if the conditions are pre-computed.

if condition1:
    do stuff
elif condition2:
    do stuff
...
if any([condition1, condition2, ...]):
    clean_up

This would be a pain if you were evaluating the conditions as part of your if statements, because in that case you would have to evaluate them a second time for the any function...unless Python is smarter than I realise.

查看更多
登录 后发表回答