Exception handling in Python 3.x

Ethan Furman ethan at stoneleaf.us
Mon Dec 13 16:19:44 EST 2010


Ethan Furman wrote:
> Please don't top-post.
> 
> Rob Richardson wrote:
> 
>>> -----Original Message-----
>>>
>>>
>>> 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,
>  >
>  > Wouldn't your first suggestion exit after the first element in
>  > iterable?
> 
> No, it hit's return instead.

Doh -- Yes, it does.

It seems both solutions only get the first element, not all elements in 
the iterator...

Maybe this instead:

def func(iterable):
     for x in iterable:
         break
     else:
         raise ValueError("... empty iterable")
     for xx in chain((x, ), iterable):
         process(xx)

Can't say as I care for this -- better to fix the unwanted nesting in 
the tracebacks from raise.

~Ethan~



More information about the Python-list mailing list