Conditional except: blocks

Aahz aahz at pythoncraft.com
Fri Jan 2 19:16:46 EST 2004


In article <mailman.34.1073079463.12720.python-list at python.org>,
Robert Brewer <fumanchu at amor.org> wrote:
>Aahz wrote:
>> That's pretty sick.  If you really need to do that, here's a more
>> Pythonic approach:
>>=20
>>     # This goes at beginning of program
>>     # or maybe at class/instance initialization
>>     if trapErrors:
>>         exceptTuple =3D (Exception,)
>>     else:
>>         exceptTuple =3D (None,)
>>=20
>>     # 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.

<nod>

>BTW, I don't think you need a tuple at all. Might we just as well write:
>
>    if trapErrors:
>        exceptTuple =3D Exception
>    else:
>        exceptTuple =3D None
>
>?

For this purpose, yes.  But I figured one might as well make it a bit
more generic, just for the purpose of documentation.

>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.

Sure; exceptTuple is the only part that needs to be generally available.
My point was more that by setting exceptTuple early in the script, you
clarify what your program is doing.  Using a subscript selector in the
``except`` clause is an unPythonic hack, partly because it's less
maintainable.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

Weinberg's Second Law: If builders built buildings the way programmers wrote 
programs, then the first woodpecker that came along would destroy civilization.



More information about the Python-list mailing list