[Python-ideas] sentinel_exception argument to `iter`

Andrew Barnert abarnert at yahoo.com
Fri Feb 7 07:55:34 CET 2014


On Feb 6, 2014, at 22:52, Andrew Barnert <abarnert at yahoo.com> wrote:

> On Feb 6, 2014, at 22:03, Terry Reedy <tjreedy at udel.edu> wrote:
> 
>> On 2/6/2014 11:15 PM, Terry Reedy wrote:
>>>> On Fri, Feb 7, 2014 at 1:36 PM, Terry Reedy
>> 
>>>>> def __next__(self):
>>>>>  try:
>>>>>    x = self.func()
>>>>>  except Exception as exc:
>>>>>    if isinstance(exc, self.sentinel):
>>>>>      raise StopIteration from None
>>>        else:
>>>          raise
>> 
>> I just realized that the above is unnecessarily complicated because the expression that follows 'except' is not limited to a builtin exception class name or tuple thereof. (I have never before had reason to dynamically determine the exception to be caught.) So, using a third parameter, replace the 5 lines with 2.
>> 
>>   except self.stop_exception:
>>       raise StopIteration from None
> 
> Except that you don't have a stop_exception, you have a sentinel, which can be either an object or an exception type.
> 
> I'm actually not sure whether it's legal to use, say, 0 or "" as the except expression. In recent 3.4 builds, it seems to be accepted, and to never catch anything. So, if that's guaranteed by the language, it's just a simple typo to fix and your simplified implementation works perfectly.

Reading the docs, it seems like it ought to be ok. In 8.4, it just says:

'For an except clause with an expression, the expression is evaluated, and the clause matches the exception if the resulting object is "compatible" with the exception. An object is compatible with an exception if it is the class or a base class of the exception object or a tuple containing an item compatible with the exception.'

So, it seems like 0 is a perfectly valid except expression, which can be checked for compatibility with any exception and will never match. Which is perfect.


More information about the Python-ideas mailing list