Python try / finally for flow control

I am sure that this concept appeared earlier, but I can not find a good, simple answer. Does try / finally use a bad way to handle functions with multiple returned data? For example, I have


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

This seems more enjoyable than saving update () commands in a temporary variable and returning it.

+5
source share
6 answers

I would not recommend it. Firstly, because it notifyUpdated()will be called even if the code in any branch throws an exception. You need something like this to really get the intended behavior:

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

-, try , - , , . , .

, , ( ), , , . , , .

+11

try/finally , . .

:

if x:
    ret = update(1)
else:
    ret = update(2)
notifyUpdated()
return ret
+11

, , try/finally :

if x:
    result = update(1)
else:
    result = update(2)
notifyUpdated()
return result

, . try . .

+3

, . , ?

try:
    if x:
        return update(1)
    elif y:
        return update(2)
    else:
        return noUpdateHere()
finally:
    notifyUpdated() # even if noUpdateHere()!

(, ), try/finally , . , , .

+3

, - .

def notifyupdateddecorator(f):
    def inner(*args, **kw):
        retval = f(*args, **kw)
        notifyUpdated()
        return retval
    return inner

@notifyupdateddecorator
def f(x):
    if x:
        return update(1)
    else:
        return update(2)

@notifyupdateddecorator
def g(x):
    return update(1 if x else 2)
+3

http://docs.python.org/library/contextlib.html:


from contextlib import closing
import urllib

with closing(urllib.urlopen('http://www.python.org')) as page:
    for line in page:
        print line

0

All Articles