[Python-ideas] PEP 479: Change StopIteration handling inside generators

Guido van Rossum guido at python.org
Wed Nov 26 18:28:59 CET 2014


On Wed, Nov 26, 2014 at 5:59 AM, <random832 at fastmail.us> wrote:

> Out of curiosity, what explicit uses of next are pythonic?


Ones immediately enclosed in try/except StopIteration, e.g.:

  try:
      x = next(it)
      print(x)
  except StopIteration:
      print('nothing')

You could rewrite this particular one as follows:

  for x in it:
      print(x)
      break
  else:
      print('nothing')

But if you have multiple next() calls you might be able to have a single
try/except catching StopIteration from all of them, so the first pattern is
more general.

-- 
--Guido van Rossum (python.org/~guido)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20141126/d519c108/attachment.html>


More information about the Python-ideas mailing list