Indentation is a valuable aspect of how we write source code. (and in languages like Python it is more than cosmetic). The "right way" to indent is of course a matter of style and a hot topic that has been the battlefield upon which many holy wars have been fought. To each his own, until two people with different styles find they have to work together on the same body of source code. As far as detailed rules about how to indent, I am going to say nothing, but I want to discuss the indentation increment and how to get the two most common text editors (vi and emacs) to work happily together.

Tabs have been 8 spaces since time immemorial. However using an indentation increment of 8 causes code to walk off the right side of the screen much too rapidly. Values less than four are not eye grabbing enough to make code syntax clear. So, the conclusion is: use an indentation value of 4.

It would be nice if settling on an indentation value of 4 would fix everything, but the trouble is that we get tangled up with the whole issue of how tabs are handled. One approach is to just render tabs as four spaces. Another approach is to indent by 4 and use tabs as a "compression" of 8 spaces. Even if two people have agreed to use an indentation value of 4, they must also agree on how tabs are handled. The only unambiguous answer seems to be to get rid of tabs entirely and use only spaces in source files.

And this is a great time to wander off topic and discuss the whole business of code indentation and tabs. If you live in the cloistered world of your own favorite editor, you will probably find this discussion mildly perplexing. The first difficulty you may encounter is when you try to print something and find your nice indentation all botched on the page. You will find big issues when you collaborate on a project and your coworkers are using a different editor and different indentation conventions and tab schemes.

One scheme is to use a mixture of tabs and spaces in the source file, and tell the editor to indent by 4 say. In this scheme a tab will be equal to an 8 space indent and confusion will be minimal.

The ugliest scheme is to use tabs everywhere in the source file and tell the editor to render them as some fictional number of spaces (say 4), this will lead to many unpleasant surprises outside the world of illusion you have created.

The brute force scheme is to abandon tabs altogether and use spaces in the source file and just say what you mean. This works for me (and you can get this from "gvim" by using the "expandtab" option). Note that expandtab does not affect existing tabs, the :%retab command will convert them all to spaces, given that expandtab is set.


Have any comments? Questions? Drop me a line!