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

Steven D'Aprano steve at pearwood.info
Tue Mar 22 18:34:22 EDT 2016


On Tue, Mar 22, 2016 at 09:36:23PM +0100, Vito De Tullio wrote:
> Steven D'Aprano wrote:
> 
> > def test():
> >     x = sentinel = object()
> >     iterable = some_function()
> >     for x in iterable:
> >         # you know the rest
> 
> onestly, I just don't like the sentinel approach... while not perfect I 
> prefer the explicit check on the throws of the StopIteration of the next 
> function
[...]

I have no objection to the try...except approach either. Another 
approach is to call next() with a default:

first = next(iterator, sentinel)
if first is sentinel:
    empty
else:
    for x in itertools.chain([first], iterator):
        process(x)


We're spoiled for choice here: there are many ways to process an empty 
iterable separately from a non-empty one.


-- 
Steve


More information about the Python-ideas mailing list