Here is the latest refactored version of the triangle project. Using iterators and string formatting, we can get the code down to effectively 2 lines:
It is definitely harder to read, but let’s walk through it.
the FOR loop is an example of an iterator. It will iterate over range(rows) or reversered(range(rows) depending whether it is inverted or not. In plain English you could read this as: “for each in range: do…” where the sentence also has a condition (if no invert)
Similarly, the print statement is horrid! I have broken it into 3 lines simply to try to give it some clarity. In plain English: “print some formatted string if i >0, otherwise print this string”
This is cool. I really like that the previous code has been reduced to 2 lines. However, I DO NOT like that these 2 lines are quite an eyeful to read. There is a great lecture from Raymond Hettinger at US PyCon 2012 about idiomatic python (http://pyvideo.org/video/1780/transforming-code-into-beautiful-idiomatic-pytho) that is well worth checking out.
Hettinger supports iterators and expressive one-liners when they do the following:
- keep logical thought together on one line. He argues that sub-atomising a single atom of thought is not pythonic (therefore, not intuitive)
- and when read left-to-right are just as you would say it in an English sentence
Both of these cases achieve this. I am still not convinced by this however. Over time, as I become accustomed with one-line expressions I believe it will become clearer. In the meantime, when I see one-liners like this, I will remind myself to read them as English sentences.