As an example, this deeply nested code:
def frob(someargs):
if something > 2:
... # do some processing
if that == "CONNECT":
... # some more processing
if verdict in blessedsolutions:
... # even more processing
print "Happy birthday!"
I tend to write like this: def frob(someargs):
if something <= 2: return # Not our concern.
... # do some processing
if that != "CONNECT": return # Not handled here.
... # some more processing
if verdict not in blessedsolutions: return
... # even more processing
print "Happy birthday!"
I do the same thing in loops, using 'continue'. The above second example looks rather flat, but in practice the 'do some processing' statements often need identations due to conditions and loops.I added the processing to demonstrate that it's not always possible to combine conditions. And, of course this way of 'bailing out early' vs. 'nested ifs and processing' is not Python specific. The dogma that a function should have only one exit point (as proposed by 'structured programming' adepts and Pascal afficionados) often leads to deeply nested control structures and convoluted testing. Brian Kernighan has written a paper on this[1].
[1] http://www.cs.virginia.edu/~cs655/readings/bwk-on-pascal.htm...