[Python-ideas] sentinel_exception argument to `iter`

Terry Reedy tjreedy at udel.edu
Fri Feb 7 07:05:33 CET 2014


On 2/6/2014 10:01 PM, Yury Selivanov 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)))

As Chris said, 42. To change current behavior before the function raises 
an exception, the comparison of each function return to the sentinel 
would have to be changed (or eliminated). My proposal does not do that. 
It only changes behavior when there is an exception and iter has been 
told that an exception is to be treated as having the same 'I am 
finished' meaning as StopIteration.

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

"In the second form, the callable is called until it returns the 
sentinel or raises an instance of stop_iter"

If sentinel is omitted, then the callable is iterated until 'completion'

The signature is a bit awkward because 'sentinel' is positional-only and 
optional without a default. The C code must use the equivalent of *args 
and switch on the number of args passed. So the new param would probably 
have to be keyword-only. I remain in favor of the proposal.

-- 
Terry Jan Reedy



More information about the Python-ideas mailing list