[Python-ideas] except expression

Nick Coghlan ncoghlan at gmail.com
Tue Feb 18 23:56:46 CET 2014


On 19 Feb 2014 06:56, "Chris Angelico" <rosuav at gmail.com> wrote:
>
> My script is currently _very_ simplistic. It looks *only* for
> assignments, so it won't find something like this:
>
> try:
>     foo.append(args[0])
> except IndexError:
>     foo.append('')
>
> which is correct, because it's impossible to know whether foo.append()
> will raise IndexError. (Chances are it won't, especially if we know
> foo is a list, for instance.) It's not safe to directly translate that
> sort of thing. It might, however, be something worth improving, as it
> narrows the scope of the except clause. But if that same code is
> written thus:
>
> try:
>     tmp = args[0]
> except IndexError:
>     tmp = ''
> foo.append(tmp)
>
> then the script _will_ find it, and then it really is a candidate for
editing.

This example should go in the PEP - the except clause in the example code
is almost certainly too broad, but the fix is rather ugly.

With the PEP, the except clause can easily be moved inside the expression
so it doesn't cover the append() call:

    foo.append((args[0] except IndexError: ""))

Cheers,
Nick.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140219/8205c7a8/attachment-0001.html>


More information about the Python-ideas mailing list