[Python-ideas] Make return inside a finally a SyntaxError
Jan Kaliszewski
zuo at chopin.edu.pl
Sat Jul 18 03:43:43 CEST 2009
18-07-2009, 02:59 Steven D'Aprano <steve at pearwood.info> wrote:
> On Sat, 18 Jul 2009 09:41:10 am Michael wrote:
>> Here are two examples of why allowing return inside a finally block
>> is a bad idea:
>>
>> def f():
>> try:
>> return 3
>> finally:
>> return 4
>
>
> Given that the finally block is guaranteed to run after exiting the try
> block, I don't see anything objectionable about that. Surprising,
> perhaps, possibly even an artifact of the CPython implementation, but
> why is it a "bad idea" that needs to be protected against?
>
>
>
>> def f():
>> try:
>> raise Exception()
>> finally:
>> return 4
>
> That's no weirder than:
>
>
> def f():
> try:
> raise Exception()
> except Exception:
> return 4
>
> or:
>
> def f():
> try:
> raise Exception()
> except Exception:
> pass
> return 4
The problem is that finally clause is not for catching exceptions
but for doing clean-up actions. And here finally-clause *stops*
propagation of any exception! (also from lower levels!)
def f()
try:
raise KeyError
except KeyError:
raise Exception
finally:
return 4
...returns 4 without obstacles!
It's weird and missleading. I thing it's definitely a bug.
--
Jan Kaliszewski <zuo at chopin.edu.pl>
More information about the Python-ideas
mailing list