Steven D'Aprano <steve+comp.lang.pyt...@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. -- http://mail.python.org/mailman/listinfo/python-list