What does "Sparse is better than dense" mean? (Python Zen)

Alex Martelli aleax at aleax.it
Thu Jul 11 10:28:15 EDT 2002


Mark McEahern wrote:

>> Although it's in the Humor section I take the Python Zen
>> (http://www.python.org/doc/Humor.html#zen) quite seriously.
>> However I can understand what does “Sparse is better than
>> dense” means.
> 
> Here's one of my pet peeves:
> 
> if x: do_one_thing()
> 
> or:
> 
> try: foo()
> except: pass
> 
> The problem with collapsing these single statement blocks into one line is
> that it complicates visual scans of a block of code.  It certainly doesn't
> make a hill of beans difference to the compiler.

It definitely doesn't make any difference to the compiler, but
it makes a huge difference to ME, as a human reader of the code,
to avoid wasting a line and thus fitting more lines onto a screen.

This is particularly important with small screens, such as the
Sharp Zaurus' 300x200 screen or thereabous, but even on large
screens it lets me use a larger and thus more readable font for
any given amount of lines that I need to see at once on-screen.

Personally, I have no difficulty whatsoever "visually scanning"
these constructs -- the lack of any indented line under the keyword
stands out and quite effortlessly makes my eyes glide rightwards.

I MUCH prefer to use entirely blank lines for separation of
_semantically *meaningful* blocks_ of code, rather than breaking
every compound statement into more lines than needed, most
particularly when such a compound statement corresponds to
a single "compound thought".

MY pet peeve is to spell "terminate the loop when X > Y" and
similarl obviously-single concepts as TWO lines...:

    if X > Y:
        break

Consider a typical "Loop-and-a-half" (Knuth) construct with
a few statements before and after the conditional-brak:


style A:

while True:
    prelim_one()
    X = prelim_two()
    Y = another_thing(X)
    if X > Y:
        break
    yet_another(X, Y)
    prepare_next(X+Y)


style B:

while True:
    prelim_one()
    X = prelim_two()
    Y = another_thing(X)

    if X > Y: break

    yet_another(X, Y)
    prepare_next(X+Y)


Style B forgoes the wanton linebreak at the 'if' and invests
that line (plus another presumably saved elsewhere by using
no wanton breaks:-) to make the loop's exit condition stand
out much better.


I suspect we'll have (at best) to agree to disagree on the
specifics of this.

The general theme of the Subject, on which I suspect we CAN
agree (even while fighting on the specifics:-), is:

    whitespace is a precious resource.  That doesn't mean
    "hog it avidly", i.e., "make your code as dense as
    possible".  It means "invest it wisely": use spacing in
    a consistent way that enhances readability and clarity
    of your code (preferably respecting the Python Style
    Guide PEP, http://www.python.org/peps/pep-0008.html).


Alex




More information about the Python-list mailing list