[Python-ideas] except expression

Jan Kaliszewski zuo at chopin.edu.pl
Wed Feb 19 01:40:43 CET 2014


19.02.2014 01:10, Steven D'Aprano wrote:

> On Tue, Feb 18, 2014 at 12:01:29PM -0500, Alexander Belopolsky wrote:
>
>> I disagree.  It is best to leave explicit selection of exceptions to 
>> catch
>> outside of the expressions.  This is job for things like decimal or 
>> numpy
>> fp contexts.
>
> I don't understand what relevance fp contexts have here.
>
>
>> Always requiring a long camel-case name inside an expression will 
>> kill most
>> of the advantages.
>
> I doubt that. And they're not typically that long. TypeError is nine
> characters, no longer than your name :-)
>
>
>> For example, it would be nice to be able to write something like
>>
>> x = d1[key] except d2[key] except 0
>
> Which is harmful, because it masks bugs. If you want to save typing,
> define K = KeyError at the top of your module, and write:
>
> x = d1[key] except K d2[key] except K 0
>
>
> which by the way looks horrible without the colons (sorry Paul, you 
> have
> not convinced me that the Tim Peters prohibition on grit applies 
> here).
> Even with three levels of indentation, mandatory brackets, and
> colons, it still fits within 79 columns and reads quite well:
>
> if condition:
>     while something():
>         for key in sequence:
>             x = (d1[key] except KeyError: (d2[key] except KeyError: 
> 0))
>
> Take the colons and brackets out, and I think it is less readable:
>
>             x = d1[key] except KeyError d2[key] except KeyError 0
>
> and ambiguous.

+1.

Though I still like the paren-after-except syntax more. :)

     x = d1[key] except (KeyError: d2[key] except (KeyError: 0))

An advantage of this one is IMHO that:

1. first we see the basic expression (d1[key])
2. but, immediately, we notice the 'except' keyword
    ("a-ha: generally it is *d1[key]* but with reservations for
     some special cases, let's see them...")
3. then, we read what are those "special cases" (KeyError: ...)
    which visually are nicely separated from the basic expression.


Cheers.
*j


PS. Of course it could be laid out with some line breaks, e.g.:

     x = (d1[key]
          except (KeyError: d2[key]
                            except (KeyError: 0)))

PS2. Yes, I also see some visual advantages of the
paren-enclosing-whole-expression syntax when applying that
kind of layout:

     x = (d1[key]
          except KeyError: (d2[key]
                            except KeyError: 0))

PS3. Anyway, IMHO *obligatory* parens would be a good thing.  Also
because they "neutralize" the visual connotations of colon with
its typical role of block-statement indicator (as it's obvious
that a block cannot start within parens).



More information about the Python-ideas mailing list