[Python-ideas] sentinel_exception argument to `iter`

Chris Angelico rosuav at gmail.com
Fri Feb 7 07:41:32 CET 2014


On Fri, Feb 7, 2014 at 5:05 PM, Terry Reedy <tjreedy at udel.edu> wrote:
> As you showed, it is easy to construct callables that might return an
> exception before raising it from finite collections with a prev or next
> method (whether destructive or not).
>
>>>> list(iter(['spam', IndexError, 42].pop, IndexError))
> [42]
>>>> list(iter({'spam', KeyError, 42}.pop, KeyError))
> [42, 'spam']  # or [42] or ['spam'], depending on hashing
>
> For these example, I guess Ram is right in suggesting a 3rd parameter. I
> would, however, just call it something like 'exception' or 'stop_iter'.
> That would make the description

I honestly wouldn't worry. How often, in production code, will you
iterate over something that might return an exception, AND be testing
for the raising of that same exception? Or the converse - how often
would you be in a position to raise the thing you might want to
return, and be annoyed that the raised exception gets squashed into
StopIteration? Don't complicate a nice simple API for the sake of
that. If you're concerned about security implications of someone
manipulating the return values and chopping something off, then just
write your own generator:

def safe_iter(func, sentinel):
    try:
        while True:
            yield func()
    except sentinel:
        pass

This will stop when the exception's raised, but not when it's
returned. The unusual case can be covered with so little code that the
API can afford to ignore it, imo.

ChrisA


More information about the Python-ideas mailing list