[Python-ideas] sentinel_exception argument to `iter`
Terry Reedy
tjreedy at udel.edu
Fri Feb 7 09:36:51 CET 2014
More information about the Python-ideas mailing list
Fri Feb 7 09:36:51 CET 2014
- Previous message: [Python-ideas] sentinel_exception argument to `iter`
- Next message: [Python-ideas] sentinel_exception argument to `iter`
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 2/7/2014 1:52 AM, Andrew Barnert 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 wrote the above with the idea that there would be a third parameter to provide an exception. It would have to have a private default like class _NoException(Exception): pass > 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. Easy to test. The result is that a non-exception expression is syntactically legal, but not when an exception occurs. >>> try: 3 except 1: 4 3 >>> try: 1/0 except 1: 4 Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> try: 1/0 ZeroDivisionError: division by zero During handling of the above exception, another exception occurred: Traceback (most recent call last): File "<pyshell#56>", line 2, in <module> except 1: 4 TypeError: catching classes that do not inherit from BaseException is not allowed -- Terry Jan Reedy
- Previous message: [Python-ideas] sentinel_exception argument to `iter`
- Next message: [Python-ideas] sentinel_exception argument to `iter`
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-ideas mailing list