Indentation for code readability

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Fri Mar 30 21:26:50 EDT 2007


On Fri, 30 Mar 2007 18:32:02 -0500, Robert Kern wrote:

>> Some people 
>>     have a strange 
>>         idea of 
>>     "increase 
>> readability".
> 
> Please contain the snark. You didn't understand why someone might want this, and
> that's fine. But please wait until you get a response before assuming that there
> could be no good reason for wanting this.

No, I think the snark was justified. Even the Original Poster admitted in
his reply that when he said "increases readability", he didn't so much
mean making the code easier to read (or as he put it, "decrypt the code")
as mirror the stack depth.

The indentation might even be meaningful, but it hardly increases
readability, and I object strongly (hence the snark) to people labeling
any code convention that carries information or is useful *in any way* as
"increasing readability".

As a general technique, trying to mirror the stack depth with indentation
is doomed to failure for anything but the most trivial code. Try following
that tactic with code that pushes and pops a variable number of items onto
the stack, or mix it with other indented blocks (for, if, etc.).

In my opinion, the O.P. has got the wrong tactic -- one which doesn't
scale, doesn't cope with Python blocks, decreases readability, and is
incompatible with code pretty-printers. He has to manually keep the
indentation adjusted with the stack depth, and if he gets it wrong (which
he will for complex code) the compiler won't tell him.

That's not to say it isn't useful, if his code is small enough. But the
right tactic is, as many people have pointed out, to use context managers
to *ensure* the stack is popped the right number of times, instead of
using indentation as a proxy for stack depth.

There very well might not be a right solution in other languages, I don't
know. For short pieces of code, indents may be no worse than manually
appending the stack depth to each line as a comment, and it might even be
better. But it no more increases readability than it decreases memory
usage or makes the code run faster.



-- 
Steven.




More information about the Python-list mailing list