the PHP ternary operator equivalent on Python

rurpy at yahoo.com rurpy at yahoo.com
Thu Nov 24 20:53:47 CET 2005


Steven D'Aprano wrote:
> rurpy at yahoo.com wrote:
>
> > Fredrik Lundh wrote:
> >
> >>def convert(old):
> >>
> >>    new = dict(
> >>        CODE=old['CODEDATA'],
> >>        DATE=old['DATE']
> >>        )
> >>
> >>    if old['CONTACTTYPE'] == 2:
> >>        new['CONTACT'] = old['FIRSTCONTACT']
> >>    else:
> >>        new['CONTACT'] = old['SECONDCONTACT']
> >>
> >>    return new
> >
> >
> > I don't find your code any more readable than the OP's
> > equivalent code:
> >
> > def convert(old):
> >     new = {
> > 	CODE: old['CODEDATA'],
> > 	DATE: old['DATE'],
> > 	CONTACT: old['FIRSTCONTACT'] \
> > 	    if old['CONTACTTYPE'] == 2 \
> > 	    else old['OLDDCONTACT']
> > 	}
> >     return new
>
>
> The problem I have with your code is that it is too
> similar to:
>
> def convert(old):
>      new = {
>          CODE: old['CODEDATA'],
>          DATE: old['DATE'],
>          CONTACT: old['FIRSTCONTACT'] }
>      if old['CONTACTTYPE'] == 2:
>      else: old['OLDDCONTACT']
>      return new

Huh?  How is this similar?  Even a glance shows the
indentation is different.  It has the same results?
Ok.  But why would someone want to assign wrong
values to some of the entries, then go back and fix them?
I think either Fredrick's code or the code I posted is
clearer than this.

> Yes, the above code is broken. But it *looks* right, at
> first glance,

Yes, I see the error.  OLDDCONTACT should be
OLDCONTACT.  Are you going to suggest Enum's? :-)

> unless you train yourself to never write
>
> if cond: TRUE_CLAUSE
> else: FALSE_CLAUSE
>
> as a two-liner.

Oh, that error too... But that error is a compile time
syntax error.  Your argument would be much stronger
if it was not a syntax error, but resulted in erroneous
program behavior.

> Regardless of whatever benefits the ternary operator is
> going to have, in my opinion allowing people to write
> TRUE_CLAUSE if COND else FALSE_CLAUSE will increase the
> amount of poorly written, hard to read code.

1. Your definitions of hard to read are not the same as mine.
2. Good documentation can mitigate this somewhat.
3. The benefits of being able to write easier to read code
  by people with good judgement outweighs the downside.




More information about the Python-list mailing list