Try, except...retry?

Peter Otten __peter__ at web.de
Thu Nov 13 04:27:17 EST 2003


Robert Brewer wrote:

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

retry does remind me of VBA's on error goto ... resume [next] a little too
much. You lose track of the actual program flow too fast. To me, the first
variant appears much clearer in that it has only code in the try clause
that is actually supposed to
fail. Also, in

try:
    setWeapon("Doug", u"satire")        
except KeyError:
    allPiranhas["Doug"] = Goldfish()
    retry

where would you want to jump? Should setWeapon() be executed in a way
similar to generators, saving its state in case of an exception instead of
a yield? Sometimes you can *not* execute a statement twice in a reliable
manner.

Peter




More information about the Python-list mailing list