the PHP ternary operator equivalent on Python

Daniel Crespo dcrespo at gmail.com
Wed Nov 23 10:01:58 EST 2005


> 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.
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 = {}

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

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).

Daniel




More information about the Python-list mailing list