Re:The Python IAQ: Infrequently Answered Questions
by TallGuyShort on Friday November 12, 2010 @08:46AM
(#1897580)
Incidentally, most C-style-syntax languages have a ternary conditional operator, and I use it quite a lot for things like building strings, very small conditionals, etc.... When used correctly, it can improve readability and expressiveness quite a bit.
x = <test> ? <result> : <alternative>
Some times for slightly more complex expressions, I'll put them on separate lines so as to have a very compact if/else structure.
Re:The Python IAQ: Infrequently Answered Questions
by adambyrtek on Friday November 12, 2010 @10:47AM
(#1897993)
It's worth noting that Peter himself mentions that most of the ternary tricks he describes are not very readable and wouldn't be considered Pythonic.
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Personally I'd hate to see something like that in any real-world project. (test and [result] or [alternative])[0]
Re:The Python IAQ: Infrequently Answered Questions
by cema on Friday November 12, 2010 @12:39PM
(#1898416)
Depending on the language, it could be an idiom.
Re:The Python IAQ: Infrequently Answered Questions
by IgorPartola on Friday November 12, 2010 @08:59AM
(#1897631)
As pointed out in the OP, there are actually quite a lot of ways to simulate the ternary operator in Python. An interesting one is (result, alternative)[test]. If result and alternative are functions you could write it as (result, alternative)[test]().
And for desert: I love this syntax:
if 0 < x <= 100: pass
For more info see: http://stackoverflow.com/questions/394809/python-ternary-ope...
As for content of the Python IAQ, I've enjoyed learning about two python idioms I had never known possible:
1. The ternary conditional operator:
x = <result> if <test> else <alternative>
2. Using or to assign an alternative value when the first is False or None
x = <option> or <option>