The rap against "while True:" loops

Paul Rubin http
Wed Oct 14 23:07:53 CEST 2009


Raymond Hettinger <python at rcn.com> writes:
> IIRC, the C++ admonition against using exceptions for flow control
> was rooted in performance concerns specific to that language and
> its compilers.  It was not stylistic advice and did not deny that
> flow control exceptions could provide elegant solutions to some
> programming challenges.

I've been wondering about that.  I know that Java exceptions are
ridiculously expensive but I didn't realize it was so bad with C++.

> Python's IndexError and KeyError are all about flow control.
> The notion is deeply embedded in the language and it would
> be a disservice to advise people to not use the language as
> designed.

Well, usually they're wrapped in iterators etc.

> So instead, we have this idiom:
> 
>     while True:
>         s = f.read(blocksize)
>         if not s:
>             break
>         ...

Well,

   while iter(lambda: f.read(blocksize), ''): 

evolved because of the awkwardness of that idiom...

> "The Little MLer" -- a chunk of this book is devoted to showing
> how exceptions can simplify code that would otherwise be
> somewhat awkward to express (the remainder of the book is devoted
> to thinking about types and how to compose program components).

Interesting--I've been wanting to look at that book.  I wonder whether
its uses of exceptions could mostly be better handled with coroutines.

> "Structured Programming with go to Statements" by Donald Knuth
> has an in-depth comparative analysis of many different looping
> constructs.

Found some pdf's: 

 http://scholar.google.com/scholar?cluster=17368311454828547380

Keep in mind that the article is 35 years old though, and is purely
imperative.  Lots of stuff done with cockamamie looping constructs is
more cleanly done with Python generators, itertools, higher-order
functions, etc.



More information about the Python-list mailing list