Conditional except: blocks
Robert Brewer
fumanchu at amor.org
Fri Jan 2 16:31:51 EST 2004
Aahz wrote:
> That's pretty sick. If you really need to do that, here's a more
> Pythonic approach:
>
> # This goes at beginning of program
> # or maybe at class/instance initialization
> if trapErrors:
> exceptTuple = (Exception,)
> else:
> exceptTuple = (None,)
>
> # some time later
> try:
> return nextHandler(args)
> except exceptTuple, exc:
> # Handle exception
Sure, sure. The point was not so much the JIT tuple-unpacking as it was
the (conditional) use of None in the "except" expression.
BTW, I don't think you need a tuple at all. Might we just as well write:
if trapErrors:
exceptTuple = Exception
else:
exceptTuple = None
?
FWIW (and just to start a flame war ;) I tend to avoid using a flag
(like 'trapErrors'), only to trigger such an intermediate step as the
above. I get antsy when that intermediate value gets used "some time
later". If I were to do something like the above, it would be put
immediately before the actual use. The other option would be to have
whoever is setting trapErrors (to True or False) instead directly set
exceptTuple to Exception, None, or what-have-you.
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list