[Python-ideas] Control Flow - Never Executed Loop Body

Stephen J. Turnbull stephen at xemacs.org
Mon Mar 21 04:01:20 EDT 2016


Émanuel Barry writes:
 > > From Vito De Tullio

 > > shouldn't it be more "pythonic" to just have a "falsy" value for
 > > an "empty" iterator?
 > 
 > Not trivial, indeed. Consider the following:
 > 
 > def gen():
 >     while random.choice([0, 1]):
 >         yield "spam"

AFAICS the OP's idea has a trivial and efficient expansion:

    for item in iterable:                # implements __next__
        # do for each item
    empty:
        # do exactly when iterable raises StopIteration on the first pass

becomes

    item = _sentinel = object()
    for item in iterable:
        # do for each item
    if item is _sentinel:
        # do exactly when iterable raises StopIteration on the first pass

(works in light testing but maybe I've missed something).  But to me
that means saving one line and a few characters in the trailer clause
is not worth syntax.

 > Is it empty? Is it not? You can't tell when it will be, and while that is a
 > bad example (I hope something like that doesn't get used!),

Replace random with polling an input source or accessing a database,
and you get the same nondeterminism.

Steve



More information about the Python-ideas mailing list