[Python-ideas] sentinel_exception argument to `iter`
Andrew Barnert
abarnert at yahoo.com
Fri Feb 7 07:52:00 CET 2014
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.
>
>>>> if x == self.sentinel:
>>>> raise StopIteration
>>>> else:
>>>> return x
>
> --
> Terry Jan Reedy
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
More information about the Python-ideas
mailing list