gen_yield_from.py 949 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. # Case of terminating subgen using return with value
  2. def gen():
  3. yield 1
  4. yield 2
  5. return 3
  6. def gen2():
  7. print("here1")
  8. print((yield from gen()))
  9. print("here2")
  10. g = gen2()
  11. print(list(g))
  12. # Like above, but terminate subgen using StopIteration
  13. def gen3():
  14. yield 1
  15. yield 2
  16. raise StopIteration
  17. def gen4():
  18. print("here1")
  19. print((yield from gen3()))
  20. print("here2")
  21. g = gen4()
  22. print(list(g))
  23. # Like above, but terminate subgen using StopIteration with value
  24. def gen5():
  25. yield 1
  26. yield 2
  27. raise StopIteration(123)
  28. def gen6():
  29. print("here1")
  30. print((yield from gen5()))
  31. print("here2")
  32. g = gen6()
  33. print(list(g))
  34. # StopIteration from within a Python function, within a native iterator (map), within a yield from
  35. def gen7(x):
  36. if x < 3:
  37. return x
  38. else:
  39. raise StopIteration(444)
  40. def gen8():
  41. print((yield from map(gen7, range(100))))
  42. g = gen8()
  43. print(list(g))