I just created a feature proposal on the CPython issue tracker and I'm curious about what the community thinks. The idea is to introduce a block similar to `finally` that only executes if one of the `if` or `elif` conditions matched. This is how it might look in code:
```python
if cond1:
# do A
elif cond2:
# do B
finally:
# do C (only runs if cond1 or cond2 matched)
# do D (always runs, regardless of conditions)
```
Currently, to achieve similar functionality, you have to use a flag like `matched = True` to track whether any condition matched. Here's what that looks like:
```python
matched = False
if cond1:
# do A
matched = True
elif cond2:
# do B
matched = True
if matched:
# do C (only runs if cond1 or cond2 matched)
# do D (always runs)
```
I'm unsure if `finally` is the best keyword for this concept, but it effectively conveys the idea. Do you think this could be a sensible addition to Python?
2 Answers
This idea sounds dubious to me without a solid real-world use case backing it up. I feel like there are better techniques or existing language features that could handle this need more effectively. Maybe something like an early exit might serve your purposes better?
Having a `finally` block execute only on matches would go against its standard behavior, which is meant to run regardless of matches. I think you could just wrap your `if` structure in a `try/finally` block if you're looking for that behavior.
Exactly! It makes more sense to keep the semantics clear rather than creating a new confused syntax.