Tertiary Operation

Christophe chris.cavalaria at free.fr
Tue Oct 17 11:01:24 EDT 2006


abcd a écrit :
> x = None
> result = (x is None and "" or str(x))
> 
> print result, type(result)
> 
> ---------------
> OUTPUT
> ---------------
> None <type 'str'>
> 
> 
> y = 5
> result = (y is 5 and "it's five" or "it's not five")
> 
> 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.
> 

the "<condition> and <if_true> or <if_false>" is NOT a ternary operator 
but an ugly hack that breaks in some situations. It just happens that 
you stumbled on one of those situations : <if_true> must never evaluate 
as False. Please, do not use that ugly hack anymore and do a proper if 
block.

Or use Python 2.5 with the official ternary operator ;)




More information about the Python-list mailing list