0

Take the following example:

def test():
  return "test"
  yield "yield"

for x in test():
  print(x)

print(next(test()))

Output:

Traceback (most recent call last):
  File ".\generator.py", line 7, in <module>
    print(next(test()))
StopIteration: test

This suprised me as i expected the iterator to yield "test" and then stop on the next iteration. What is the reasoning behind this? What is it useful for?

MennoK
  • 436
  • 3
  • 10
  • 1
    Does this answer your question? [Return in generator together with yield in Python 3.3](https://stackoverflow.com/questions/16780002/return-in-generator-together-with-yield-in-python-3-3) – go2nirvana Dec 11 '20 at 11:07
  • I looked at that post and the linked pep. They explain how it works, but not the reason behind why it works, so it does not answer my question. – MennoK Dec 11 '20 at 11:15
  • PEP has a 'rationale' section https://www.python.org/dev/peps/pep-0380/#rationale In this case the answer for 'why it works' is 'it was designed to work exactly like that'. What you experience is not some kind of flaw, but specifically designed behaviour. Maybe ask once again, try to be more precise, i'll do my best to answer. – go2nirvana Dec 11 '20 at 11:21
  • Ah i overlooked that part, it does answers my question, thanks! – MennoK Dec 11 '20 at 11:31

0 Answers0