Exception handling in Python 3.x

Paul Rubin no.email at nospam.invalid
Mon Dec 6 16:13:40 EST 2010


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.



More information about the Python-list mailing list