Ethan Furman <et...@stoneleaf.us> writes: > Ethan Furman wrote: >> Arnaud Delobelle wrote: >>> >>> 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") >> >> >> For the immediate case this is a cool solution. > > > Drat -- I have to take that back -- the OP stated: > >> The intention is: >> >> * detect an empty iterator by catching StopIteration; >> * if the iterator is empty, raise a ValueError; >> * otherwise process the iterator. > > > Presumably, the print(x) would be replaced with code that processed > the entire iterable (including x, of course), and not just its first > element.
As I had stated before, I didn't where the discussion started from. I replied to code posted by Steven D'Aprano and Paul Rubin. My code snippet was equivalent in functionality to theirs, only a little simpler. Now if one wants to raise an exception if an iterator is empty, else process it somehow, it must mean that the iterator needs to have at least one element for the processing to be meaningful and so it can be thought of as a function of one element and of one iterator: process(first, others) which never needs to raise an exception (at least related to the number of items in the iterator). Therefore you can write your function as follows: def func(iterable): iterator = iter(iterable) for first in iterable: return process(first, iterator) else: raise ValueError("need non-empty iterable") -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list