Weird exception handling behavior -- late evaluation in except clause

Steven D'Aprano steve+comp.lang.python at
Mon Dec 3 08:30:26 CET 2012

On Mon, 03 Dec 2012 16:24:50 +1100, Chris Angelico wrote:

> On Mon, Dec 3, 2012 at 8:31 AM, Steven D'Aprano
> <steve+comp.lang.python at> wrote:
>> Consider this piece of legal Python code:
>> Err = None
>> if condition(x) > 100:
>>     Err = OneException
>> elif another_condition(x):
>>     Err = AnotherException
>> try:
>>     spam(a, b, c)
>> except Err:
>>     recover()
> Legal it may be, but are there times when you actually _need_ this level
> of dynamism? It strikes me as a pretty weird way of going about things.
> I agree with the point you're making, but this feels like a contrived
> example, and I'm curious as to whether it can be uncontrived.

Yeah, in hindsight it was a pretty crappy example. But this sort of 
dynamism really is useful:

def testRaises(exc, func, *args):
        result = func(*args)
    except exc:
    raise AssertionError("expected exception but didn't get one")

def wrap(func, exc, default=None):
    def inner(*args):
            return func(*args)
        except exc:
            return default
    return inner


More information about the Python-list mailing list