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.
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:
notifyUpdated()
try: if x: return update(1) else: return update(2) except: raise else: notifyUpdated()
-, try , - , , . , .
try
, , ( ), , , . , , .
try/finally , . .
:
if x: ret = update(1) else: ret = update(2) notifyUpdated() return ret
, , try/finally :
if x: result = update(1) else: result = update(2) notifyUpdated() return result
, . try . .
, . , ?
try: if x: return update(1) elif y: return update(2) else: return noUpdateHere() finally: notifyUpdated() # even if noUpdateHere()!
(, ), try/finally , . , , .
try/finally
, - .
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)
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