[Python-ideas] Python-ideas Digest, Vol 131, Issue 106
Steven D'Aprano
steve at pearwood.info
Tue Oct 31 03:46:48 EDT 2017
On Tue, Oct 31, 2017 at 06:02:34PM +1100, Chris Angelico wrote:
> > def single(i):
> > try:
> > v =i.next()
> > except StopIteration:
> > raise ValueError('No items')
> > try:
> > i.next()
> > except StopIteration:
> > return v
> > else:
> > raise ValueError('More than one item')
> >
> > print single(name for name in('bob','fred') if name=='bob')
Seems like an awfully complicated way to do by hand what Python already
does for you with sequence unpacking. Why re-invent the wheel?
> Thanks :)
>
> One small change: If you use next(i) instead of i.next(), your code
> should work on both Py2 and Py3. But other than that, I think it's
> exactly the same as most people would expect of this function.
Not me. As far as I can tell, that's semantically equivalent to:
def single(i):
result, = i
return result
apart from slightly different error messages.
--
Steve
More information about the Python-ideas
mailing list