Tertiary Operation

Bruno Desthuilliers onurb at xiludom.gro
Tue Oct 17 17:04:45 CEST 2006


abcd wrote:
> x = None
> result = (x is None and "" or str(x))

You don't need the parenthesis.

> print result, type(result)
> 
> ---------------
> OUTPUT
> ---------------
> None <type 'str'>
> 
> 
> y = 5
> result = (y is 5 and "it's five" or "it's not five")

By all means *don't* use identity tests in such a context. Try with
100000 instead of 5:
>>> x = 100000
>>> x is 100000
False
>>>

> print result
> 
> -------------
> OUTPUT
> -------------
> it's five
> 
> ...what's wrong with the first operation I did with x?  I was expecting
> "result" to be an empty string, not the str value of None.

As other already pointed, an empty string (as well as an empty list,
tuple, dict, set IIRC, and zero int or float) evals to False in a
boolean context.

Python 2.5 has a ternary operator. If you need to deal with older Python
versions, another possible 'ternary op hack' is :

x = None
(str(x), "")[x is None]
=> ""
x = 42
(str(x), "")[x is None]
=> "42"

This relies on the fact that False == 0 and True == 1.

NB : if you don't want to eval both terms before (which is how it should
be with a real ternanry operator), you can rewrite it like this:

result = (str, lambda obj:"")[x is None)(x)

But this begins to be unreadable enough to be replaced by a good old
if/else...

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list