catching exceptions in expressions

Andrew Dalke adalke at mindspring.com
Thu Aug 7 15:50:38 EDT 2003


Vaclav Dvorak:
> Well, list comprehensions were implemented, and that feature didn't even
> need anything new - not even functions, let alone syntax:

True, which is why I did say "generally."

When list comprehensions came out, one of the things I found
I liked about it was it replaced a lot of code like

new_data = []
for x in data:
    new_data.append(x.attr)
data = new_data

I tried to abstract that into a function, like

def get_list_attr(data, attrname):
  new_data = []
  ...

but could never come up with a good name for that function.
List comprehensions made the code shorter, easier to read,
and solved my naming problem.

While what you want has a meaningful name, like
 'safe_int' or 'int_with_default' or ....

> Well, it's good when you will use than a hundred times. But when you
> need it only here and there, it's more hassle than it's worth.

Your syntax-based default value on exception could have the same
principle applied to it - is the number of times of use worth making
the change to the language?

> >>a = int(s) or 99 if ValueError
> >
> > Parse ambiguity.

>
> I'm not an expert in parsers, but wouldn't the "if" disambiguate it, as
> it's not otherwise found inside expressions?

In general, yes.  But Python uses a lookahead-one parser, meaning
that the next token should be sufficient to figure things out.  Suppose
you have

   x = a or b or [....]

is the last or part of the 'or' expression

   x = a or b or c

or is it part of an exception catcher

   x = a or b or c if ValueError

Parsers can figure things out, but that makes the code harder to
implement and the language harder to read.

> >>except ValueError:
> >>         continue [execution on next line - my comment]
> > 'continue' already has meaning in current Pythons.
>
> That's why I chose that - no new keyword. But I retract this one, and
> the "retry" statement too. I don't really like them myself. :-)

What I meant is that

for x in data:
  try:
    f(x)
  except ValueError:
    continue
  ..
already has meaning in Python, not that the word 'continue' by
itself exists as a keyword.

> Why? You're the only one who doesn't like it, so far. ;-) Of course,
> you're also the only one who voiced any opinion, so that leaves me with
> a not so huge statistical sample of one. :-)

Plenty of history using Python and reading c.l.py and seeing
discussions about changing the syntax before, and seeing an utter
dearth of people asking for this sort of feature, and applying my
own sense of sensability and estimating how rarely I would use
the construct.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list