Skip to content

Comment on The Python IAQ: Infrequently Answered Questions

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.

   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]

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:

  if 0 < x <= 100: pass
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 ?

AboutSource Built by g1lg1l

Hackerly is an independent reader for Hacker News, built on the public HN API. Not affiliated with Y Combinator.