Try, except...retry?

Robert Brewer fumanchu at amor.org
Wed Nov 12 20:20:08 EST 2003


Alex Martelli wrote in another thread:

> One sign that somebody has moved from "Python newbie" to "good Python
> programmer" is exactly the moment they realize why it's wrong to code:
> 
>     try:
>         x = could_raise_an_exception(23)
>         process(x)
>     except Exception, err:
>         deal_with_exception(err)
>     proceed_here()
> 
> and why the one obvious way is, instead:
> 
>     try:
>         x = could_raise_an_exception(23)
>     except Exception, err:
>         deal_with_exception(err)
>     else:
>         process(x)
>     proceed_here()

I just got there, Alex. :) However, it got me thinking. I keep running
into cases like:

try:
    aPiranha = allPiranhas['Doug']
except KeyError:
    aPiranha = Pirhana()
    allPiranhas['Doug'] = aPiranha
aPiranha.weapon = u'satire'

which would, in my opinion, be better written (i.e. *clearer*) as:

try:
    allPiranhas['Doug'].weapon = u'satire'
except KeyError:
    allPiranhas['Doug'] = Pirhana()
    retry

Of course, there are other ways of doing it currently, most notably with
1) a while loop and a retry flag, or 2) just repeating the assignment:

try:
    allPiranhas['Doug'].weapon = u'satire'
except KeyError:
    allPiranhas['Doug'] = Pirhana()
    allPiranhas['Doug'].weapon = u'satire'

Yuck to both.

Current docs, 4.2 Exceptions says, "Python uses the ``termination''
model of error handling: an exception handler can find out what happened
and continue execution at an outer level, but it cannot repair the cause
of the error and retry the failing operation (except by re-entering the
offending piece of code from the top)." I'm proposing that 'retry' does
exactly that: reenter the offending piece of code from the top. Given
the aforementioned pressure to reduce try: blocks to one line, this
could become a more viable/common technique.

Quick Googling shows I'm not the first with this concept:
http://mail.zope.org/pipermail/zope-checkins/2001-November/008857.html

Apparently Ruby has this option? Gotta keep up with the Joneses. :) I'm
not enough of a Pythonista yet to understand all the implications of
such a scheme (which is why this is not a PEP), so I offer it to the
community to discuss.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org





More information about the Python-list mailing list