try/except/else flexibility...
Raymond Hettinger
python at rcn.com
Fri Apr 12 23:58:21 EDT 2002
"Magnus Lie Hetland" <mlh at vier.idi.ntnu.no> wrote in message
news:slrnabcon3.g5r.mlh at vier.idi.ntnu.no...
> Just a thought: Given the prevalence of try/except/else in the "don't
> look before you leap" way of doing things, could it be useful to make
> the statement more flexible? For instance, instead of writing
>
> try: foo + ''
> except: pass
> else: bar()
>
> (assuming I'm sloppy enough not to specify TypeError on the second
> line) one could simply write:
>
> try: foo + ''
> else: bar()
Hmm, trading explicitness for brevity and flexibility. How about
meeting you halfway:
ignore TypeError: foo + ''
else: bar()
>
> and if I want something done only if it causes no exceptions, for
> instance pop off an element of a list unless it is empty, I could just
> do:
>
> try: somelist.pop()
ignore IndexError: somelist.pop()
Raymond Hettinger
More information about the Python-list
mailing list