[Python-ideas] Retrying EAFP without DRY

Nick Coghlan ncoghlan at gmail.com
Wed Jan 25 01:04:37 CET 2012

On Wed, Jan 25, 2012 at 4:45 AM, Mike Meyer <mwm at mired.org> wrote:
> Which is not a code smell. However, if you can tell by reading the
> code that it will only run once (or never run), like this one:
>     for i in range(1):
> Then it's a code smell!

I agree specifically in regards to range() with a literal argument,
but it really depends on the iterator. Using break to force a single
iteration can be nicer than calling next() and catching StopIteration.
For example, code like the following makes it easy to special case the
first entry in an iterator:

    walk_iter = os.walk(topdir)
    for dirpath, files, subdirs in walk_iter:
        # Special case the top level directory
       raise RuntimeError("No dir entry for {!r}".format(topdir))
    for dirpath, files, subdirs in walk_iter:
        # Process the subdirectories

Python has very powerful looping constructs already - we don't need
more just because some folks have been trained to think that break and
continue are evil and haven't considered whether or not these
prejudices inherited from C and C++ are still relevant in Python. Like
early returns, break and continue are potentially dangerous in C and
C++ because having multiple exit points from a scope increases the
chance of leaking memory (or some other resource). By contrast,
garbage collection and context managers mean that making appropriate
use of early returns, break and continue is quite easy and safe in
Python (and often clearer than the alternatives that try to avoid


Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia

More information about the Python-ideas mailing list