On 02/19/2014 07:01 AM, Paul Moore wrote:
I think this is pretty much a tangent by now, but your interpretation here isn't the only way of looking at things. Consider the following alternative way of looking at it
TRUE-EXPR if COND else FALSE-EXPR
Here, TRUE-EXPR is the "expected" result, qualified by the possibility that if COND isn't true then FALSE-EXPR is the result. Looking at the if expression in that way, the parallel with the exception expression is much clearer:
EXPR except EXCEPTION return FALLBACK
Here, EXPR is the "expected" result, but if you get EXCEPTION when evaluating it then use FALLBACK instead. (Feel free to replace "return" with colon or your favourite syntax alternative).
-1 on return. I expect that to exit the function where ever it is in the current scope. How about this?
def catch_else(exc, e1, e2): ... try: ... return e1() ... except exc: ... return e2() ... catch_else(IndexError, lambda: [1, 2, 3][2], lambda: 0) 3 catch_else(IndexError, lambda: [1, 2, 3][4], lambda: 0) 0
The only bad thing about that is having to spell out lambda for each of the arguments. *1 With a short literal form for a lambda that takes no arguments. value = catch_else(exc, \expr1, \expr2) #alternatives to '\'? The function "catch_else" could be a builtin or in functools depending on how useful it's believed to be. The shorter lambda expression literal... or expression quote as it's referred to in other languages would be useful on it's own, and more preferable than a full lambda for things like this. [*1] In discussion about how long it's taken for us to get away from incandescent lights, the expert brought up that there is a difference between acceptable and preferable. Cheers, Ron