the PHP ternary operator equivalent on Python

Steven D'Aprano steve at
Wed Nov 23 23:02:51 CET 2005

On Wed, 23 Nov 2005 07:01:58 -0800, Daniel Crespo wrote:

>> WHY WHY WHY the obsession with one-liners? What is wrong with the good old
>> fashioned way?
>> if cond:
>>    x = true_value
>> else:
>>    x = false_value
> Let me tell you something: I'm not a one-liner coder, but sometimes It
> is necesary.

I'm not arguing for multi-line code just for the sake of using more than
one line. I'm against artificially trying to compress a algorithm that is
naturally expressed in two or more lines into one line.

> For example:
> I need to translate data from a DataField to Another.
> def Evaluate(condition,truepart,falsepart):
>     if condition:
>         return truepart
>     else:
>         return falsepart
> dOldDataFields = {}
> dNewDataFields = {}

Why do you bother to initialise dNewDataFields to an empty dict when you
then populate it in the very next statement?

> dNewDataFields = {
>             'CODE':	dOldDataFields['CODEDATA'],
>             'DATE':	dOldDataFields['DATE'],
>             'CONTACT':	Evaluate(dOldDataFields['CONTACTTYPE']==2,
> dOldDataFields['FIRSTCONTACT'], dOldDataFields['SECONDCONTACT'])
> }

Doesn't look like a one-liner to me. You've called Evaluate, which takes
five lines by my count. 

> With this, I created a new dic very easy, saving in
> dNewDataFields['CONTACT'] the value of dOldDataFields['FIRSTCONTACT']
> or the value of dOldDataFields['SECONDCONTACT'] depending on
> dOldDataFields['CONTACTTYPE']. How you do this in a practic way without
> the use of one-line code? It is needed! You can't avoid it! Even using
> a = [if_false_expr, if_true_expr][predicate] or a function, you'll
> always have to use a one-line code (for this purpose, of course).

Again, I am not arguing for needlessly inflating lines of code, I think
your solution is fine. But just to prove it can be done:

dNewDataFields['CODE'] = dOldDataFields['CODEDATA']
dNewDataFields['DATE'] = dOldDataFields['DATE']
if dOldDataFields['CONTACTTYPE'] == 2:
    dNewDataFields['CONTACT'] = dOldDataFields['FIRSTCONTACT']
    dNewDataFields['CONTACT'] = dOldDataFields['SECONDCONTACT']

There. The world didn't end. 



More information about the Python-list mailing list