Exception handling in Python 3.x

Arnaud Delobelle arnodel at gmail.com
Mon Dec 13 14:09:22 EST 2010


Paul Rubin <no.email at nospam.invalid> writes:

> Steven D'Aprano <steve+comp.lang.python at pearwood.info> writes:
>> Apart from this horrible idiom:
>>
>> def func(iterable):
>>     it = iter(iterable)
>>     failed = False
>>     try:
>>         x = next(it)
>>     except StopIteration:
>>         failed = True
>>     if failed:
>>         raise ValueError("can't process empty iterable")
>>     print(x)
>>
>>
>> or similar, is there really no way to avoid these chained exceptions?
>
> Seems like yet another example of people doing messy things with
> exceptions that can easily be done with iterators and itertools:
>
>     from itertools import islice
>
>     def func(iterable):
>       xs = list(islice(iter(iterable), 1))
>       if len(xs) == 0:
>          raise ValueError(...)
>       print xs[0]
>
> It's really unfortunate, though, that Python 3 didn't offer a way to
> peek at the next element of an iterable and test emptiness directly.

I missed the start of this discussion but there are two simpler ways:

def func(iterable):
    for x in iterable:
        print(x)
        return
    raise ValueError("... empty iterable")

Or using 3.x's next's optional second argument:

_nonext=object()
def func(iterable):
    x = next(iter(iterable), _nonext)
    if x is _nonext:
        raise ValueError("... empty iterable")
    print(x)

-- 
Arnaud



More information about the Python-list mailing list