
On Sat, Mar 2, 2013 at 2:45 PM, Alan Johnson <alan@breakrs.com> wrote:
try with context_manager(): … bunch of code … except: … exception handler …
This optimization saves a colon and some white space and mixes two unrelated concepts. The try/except pattern I want to optimize is try: x = expr1 except ValueError: x = expr2 For example: expr1 except ValueError else expr2 or try expr1 except ValueError else expr2 This is particularly useful in cases like this: a = ((try t.x except AttributeError else 0) + (try t.y except AttributeError else 0) + (try t.z except AttributeError else 0)) where standard try/except requires 13 lines and is much harder to read. Yes, this can be done with a function and two lambdas (and I've done it this way): try_except(lambda: expr1, ValueError, lambda: expr2) def try_except(value, exceptions, otherwise): try: return value() except exceptions or Exception: return otherwise() --- Bruce Learn how hackers think: http://j.mp/gruyere-security