"Early exit" is a perfectly Pythonic style (when warranted: gnibbler's answer correctly points out that for your specific use case there's a built-in [[in Python 2.5 and better]] that's preferable) and often helps realize the Pythonic goal of "flat is better than nested". And for
is usually the right way to do looping in Python, at application-level: if there's any complicated loop logic (as might warrant a while
), it's often better to push it down to an auxiliary generator anyway.
Advantages sometimes claimed for the alternative "single point of exit" include the existence of a single "exit bottleneck" at which clean-up can be performed. But since exceptions are always possible, you don't know that your single return
is a unique exit bottleneck, even if you have it: the proper way to ensure good cleanup is, instead, the with
statement (in 2.6, or 2.5 with an "import from the future"; for older versions of Python, the clunkier but still useful try
/finally
instead).
Knuth's article "Structured Programming With Goto Statements" (pdf) -- an incredible, visionary article from 1974 by the man that many consider a living legend of computer science, both theoretical and practical -- is well worth reading. Anybody who doubts the article's applicability to Python should consider the following short quote from it:
devices like indentation, rather than
delimiters, might become feasible for
expressing local structure in the
source language.
twenty years before Python 1.0 was published, Knuth already foresaw the key syntax aspect that was to become such a hallmark of Python (and, independently, Haskell, released a bit earlier than Python -- from personal discussion with Knuth, Peyton Jones, and van Rossum, I can attest they all claim that these three inventions of "indentation for grouping" were entirely independent from each other, just a case of "great minds think alike" -- or, in Charles Fort's words, "it was just steam engine time";-).
Formal proofs of code including early exit are of course not a jot harder than for equivalent code with single point of exit, if nothing else because the famous proof by Corrado Böhm and Giuseppe Jacopini shows how to perform a mechanical transformation from any flowchart to one containing only sequence, selection and repetition (but of course the transformed program -- just like any other program trying to avoid the early-exit style -- is prone to having more nesting than needed, and extra boolean "status" variable, which interfere with readability, directness, and efficiency -- making early-exit much superior in languages that support it well).