Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python try/finally for flow control

I'm sure this concept has come up before but I can't find a good, simple answer. Is using try/finally a bad way to handle functions with multiple returns? For example I have


try:
    if x:
        return update(1)
    else:
        return update(2)
finally:
    notifyUpdated()

This just seems nicer than storing update() commands in a temporary variable and returning that.

like image 368
Falmarri Avatar asked Aug 16 '10 21:08

Falmarri


2 Answers

I wouldn't recommend it. First because notifyUpdated() will be called even if the code in either branch throws an exception. You would need something like this to really get the intended behavior:

try:
    if x:
        return update(1)
    else:
        return update(2)
except:
    raise
else:
    notifyUpdated()

Secondly, because try blocks generally indicate you're doing some kind of exception handling, and you aren't, you're just using them for convenience. So this construct will confuse people.

For example, I don't think either of the first two people (at least one of which deleted their answer) to answer your question realized what you were really trying to do. Confusing code is bad, no matter how convenient and clever it seems.

like image 123
Omnifarious Avatar answered Sep 28 '22 03:09

Omnifarious


I would not use try/finally for flow that doesn't involve exceptions. It's too tricky for its own good.

This is better:

if x:
    ret = update(1)
else:
    ret = update(2)
notifyUpdated()
return ret
like image 28
Ned Batchelder Avatar answered Sep 28 '22 03:09

Ned Batchelder