Indentation levels and line lengths (was Re: Fun python 3.2 one-liner)

Chris Angelico rosuav at
Tue Apr 5 20:09:10 CEST 2011

On Wed, Apr 6, 2011 at 3:48 AM, Steven D'Aprano
<steve+comp.lang.python at> wrote:
>> and has on occasion gone as far as 12-16.
> I would consider anything more than four indents a code smell. That is,
> four is unexceptional; five would make me look over the code to see if it
> could be refactored; six would make me look at it *carefully*; eight
> would have me questioning my own sanity. I wouldn't give a hard limit
> beyond which I would "never" go beyond, but I find it difficult to
> imagine what drugs I'd need to be on to go beyond eight.
> *wink*

Chocolate. Chocolate and heavy C code work. The alternative is to
break everything out into separate functions, which inevitably results
in heaps of unnecessary parameter-passing; granted, a C compiler will
often optimize most of it away, but it's still annoying to have to
pass a whole lot of reference parameters to a function that's only
ever called from one place.

As an example, think of a typical GUI message loop (in OS/2 or Windows):

int WndProc(HWND hwnd,int msg,int param1,int param2)
	switch (msg)
		case WM_PAINT:
			if (have_message)
		//etc, etc, etc
		default: return 0;

That's four levels of indentation right there. Now imagine that the
whole kaboodle is inside a class definition and that's a fifth, and
then it only takes a small amount of extra code complexity to hit
eight. I agree that it's a code smell, though. For something to get to
the 10 or 12 that I mentioned above, it really has to be something
with a whole lot of relatively insignificant indentations early on, so
the entire "useful logic" is contained in levels 6-10 or something;
and the 16 was probably a little artificial, in that I *could* have
refactored that function but just never got around to it (which means
it's pushing the limits of "legitimately"). But I know I've had C code
get past 10 without there being any logical reason to break some of
the code out.

The other time I have miles of indentation is when I'm working in an
unfamiliar language, and I'm not comfortable with its variable scoping
rules (hello there, PHP). That's not what I'd call "legitimate"
indentation, but I sure am glad there's no hard limit on what's

Chris Angelico

More information about the Python-list mailing list