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.
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]().
Comments
Regarding the "if thr wr any", and the rise of Haskell and Clojure, I wonder whether such caveat applies any longer.
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>
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.
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.
Personally I'd hate to see something like that in any real-world project.Depending on the language, it could be an idiom.
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:
For more info see: http://stackoverflow.com/questions/394809/python-ternary-ope..."..and the rise of Haskell and Clojure.."
Is there any real world evidence of said claim, outside geek-fetish bubbles like HN ?