[Python-ideas] sentinel_exception argument to `iter`

Chris Angelico rosuav at gmail.com
Fri Feb 7 04:11:05 CET 2014


On Fri, Feb 7, 2014 at 2:01 PM, Yury Selivanov <yselivanov.ml at gmail.com> wrote:
>
> On 2/6/2014, 9:36 PM, Terry Reedy wrote:
>>
>> I think this would be a great idea if simplified to reuse the current
>> parameter. It can work in Python because exceptions are objects like
>> anything else and can be passed as arguments. No new parameter is needed.
>
> What will the following code print:
>
>    d = deque((42, IndexError, 'spam'))
>    print(list(iter(d.popleft, IndexError)))
>
> ?

Presumably it would stop once it reaches the IndexError, exactly per
current behaviour, and print [42]. So you can't depend on it actually
having caught IndexError, any more than you can depend on it actually
having found the element:

>>> def foo():
    global idx
    idx+=1
    if idx==3: raise StopIteration()
    return idx*10
>>> idx=0
>>> print(list(iter(foo, 20)))
[10]
>>> idx=0
>>> print(list(iter(foo, 50)))
[10, 20]

It'll stop at any of three conditions: a raised StopIteration from the
function, a returned value equal to the second argument, or a raised
exception that's a subclass of the second argument. All three will be
folded into the same result: StopIteration.

ChrisA


More information about the Python-ideas mailing list