[Python-Dev] Chaining try statements: eltry?

Raymond Hettinger python at rcn.com
Wed Jul 6 22:06:06 CEST 2005


[Thomas Lotze]
> > I want to ask what you think about introducing a keyword 'eltry' 
> > which would be the counterpart of 'elif' for try statements. This 
> > had been suggested before on python-list a couple of years ago by 
> > Jonathan Gardner, but nothing (that I could find) seems to have come

> > of it.

[Guido]
> I'm -1 on this. The use case doesn't occur often in my experience and 
> IMO putting each try statement in the else clause of the previous one 
> is a fine solution.
> 
> I also notice that your only example is very repetitive, and would be 
> better written as a loop, using Python's dynamic nature:
> 
> for decoder in foo_decode, bar_decode, foobar_decode:
>     try:
>         data = decoder(data)
>         break
>     except ValueError:
>         print "data doesn't seem to be %s-encoded" % decoder.__name__

FWIW, the looping solution has worked out well in practice.  From
csv.py:

    for thisType in [int, long, float, complex]:
        try:
            thisType(row[col])
            break
        except (ValueError, OverflowError):
            pass


Raymond


More information about the Python-Dev mailing list