[Python-ideas] except expression

Chris Angelico rosuav at gmail.com
Wed Feb 19 03:09:29 CET 2014


On Wed, Feb 19, 2014 at 12:25 PM, Rob Cliffe <rob.cliffe at btinternet.com> wrote:
> Well done, Chris!  (Some poor sod does all the hard work while the rest of
> us chip in our 2c as and when we feel like it, making more work for him.  A
> bit like bear-baiting.)

It may be more work for me, but it's also the validation of that work.
This isn't a case of "little me against the throng, I'm only one and
possibly I'm wrong" [1] - it's something that's generating several
hundred emails' worth of interest. And once it quiets down here, I can
post to python-dev and start it all over again :)

> The shorter the examples, the more convincing they are.  Dramatically so.
> And you say "there are a huge number" of them.  I think this shows the value
> of the proposal.

Yep. I'd guess that there are over a hundred examples in the stdlib
that would become one-liners with this proposal. Quite a few of them
have long assignment targets like _CONFIG_VARS['abiflags'] (and there
was a longer one, but I don't have it handy), so the expression form
encourages DRY.

> Too
> bad if multiple statements on a line is almost a taboo for the rest of you
> plonkers - I know I'm right and the rest of the planet is wrong.

I'll join you on the 'right' side of the planet :) If putting two
statements on a line makes it easier to spot bugs, I'll do it.

> I have to say I'm not keen on the cases where you introduce an extra
> contraction, simply because it's possible (although the fact that the
> proposal makes it possible is sort of a point in its favour, in a perverted
> way).  E.g. given
>
>                     try:
>                         netloc_enc = netloc.encode("ascii")
>                     except UnicodeEncodeError:
>                  &nb
> sp;      netloc_enc = netloc.encode("idna")
>                     self.putheader('Host', netloc_enc)
>
>
> which would contract (consistently with the simpler examples) to:
>
>                     netloc_enc = netloc.encode("ascii") except
> UnicodeEncodeError: netloc.encode("idna")
>                     self.putheader('Host',
> netloc_enc)
>
> you go one step further and write
>
>                     self.putheader('Host',
>                         netloc.encode("ascii") except UnicodeEncodeError:
> netloc.encode("idna")
>                     )

This is where it gets strongly debatable. Obviously, since this is an
expression, it can be used in any context where an expression is
valid, not just an assignment. However, part of the issue may be that
my script was looking only for assignments. A lot of cases were
clearly worth mentioning, some others are doubtful, a number of them
just not worth the hassle. I'd like some good non-assignment examples.

ChrisA

[1] Theresa's song from The Mountebanks:
http://math.boisestate.edu/gas/gilbert/plays/mountebanks/webopera/mount_07.html


More information about the Python-ideas mailing list