Exception handling in Python 3.x

Arnaud Delobelle arnodel at gmail.com
Mon Dec 13 15:39:19 EST 2010


"Rob Richardson" <Rob.Richardson at rad-con.com> writes:

You shouldn't top-post!

> Arnaud,
>
> Wouldn't your first suggestion exit after the first element in iterable?

Yes, after printing that element, which is what the code I quoted did.

> And would your second suggestion throw an exception after normal
> processing of all elements in the interator?

No. It would have the same behaviour as the first one.

> RobR
>
> -----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

-- 
Arnaud



More information about the Python-list mailing list