For review: PEP 308 - If-then-else expression

Andrew Dalke adalke at mindspring.com
Sat Feb 8 04:10:51 CET 2003


Carlos Ribeiro:

> On Saturday 08 February 2003 12:49 am, Andrew Dalke wrote:
> > However, modifying the code is much easier.
> >
> >   descr  = b** 2 - 4*a*c
> >   if descr > 0:
> >     root_type = "real"
> >   elsif descr == 0:
> >     root_type = "duplicate"
> >   else:
> >    root_type = "imaginary"
> >   print "descriminate =", descr
> >   print "roots are", root_type
>
> I don't think that the code above is much clearer than the one-liner with
the
> ternary operator.

And I did point out that it could be written as a one-liner in existing
Python, as in

  print "roots are", ["imaginary", "duplicate", "real"][cmp(decr, 0.0)]

BTW, I think the word I should have used is "singular" and not "duplicate."
:)

> What I see is that you may be used to sequential
> programming, and so, specifying every step seems to be the "right way of
> doing it" for you. In my opinion, the only thing that the code above buys
you
> is the ability to follow it step by step, but that does not mean it's much
> clearer - only that it works a few abstraction layers below the one-liner
> with the ternary operator.

It could be.  I left the C/C++/Perl world, which had a ternary, some
5+ years ago.  I remember (mis)using the ternary operator a lot.  I've
become a better developer since then, and it's hard to determine now
if my misuses were because of my inexperience or because of intrinsic
tendency to misuse that operator.

As I mentioned elsewhere, I've scanned the Linux kernel for use
of the ?: operator.  It isn't used all that often, and most cases can
be implemented in Python with the
   [false, true][expr comparison value]
construct or with the
  x = y or default_value
construct.

> In my opinion, the best thing to do right now is to wait a few days for
things
> to settle down. I'm sure that many people that reacted against it today
will
> get used to the idea fairly quickly, specially if we come up with a
slightly
> better idiom (this one is quite good, but some good candidates for
> improvement have appeared today, and more will come).

I would rather see some better examples of when people would like
to use the if/else expression.  People have pointed out that it can do
short circuiting, but in the real-life uses I saw in the kernel it didn't
make a different if there was short circuiting or not.

> There is always reaction to change. Sometimes we get used to the new stuff
so
> fast that we can't even understand why did we react first place.

Indeed.  Though I still recall why I reacted against list comprehensions.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list