generator_close.py 987 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. def gen1():
  2. yield 1
  3. yield 2
  4. # Test that it's possible to close just created gen
  5. g = gen1()
  6. print(g.close())
  7. try:
  8. next(g)
  9. except StopIteration:
  10. print("StopIteration")
  11. # Test that it's possible to close gen in progress
  12. g = gen1()
  13. print(next(g))
  14. print(g.close())
  15. try:
  16. next(g)
  17. print("No StopIteration")
  18. except StopIteration:
  19. print("StopIteration")
  20. # Test that it's possible to close finished gen
  21. g = gen1()
  22. print(list(g))
  23. print(g.close())
  24. try:
  25. next(g)
  26. print("No StopIteration")
  27. except StopIteration:
  28. print("StopIteration")
  29. # Throwing StopIteration in response to close() is ok
  30. def gen2():
  31. try:
  32. yield 1
  33. yield 2
  34. except:
  35. raise StopIteration
  36. g = gen2()
  37. next(g)
  38. print(g.close())
  39. # Any other exception is propagated to the .close() caller
  40. def gen3():
  41. try:
  42. yield 1
  43. yield 2
  44. except:
  45. raise ValueError
  46. g = gen3()
  47. next(g)
  48. try:
  49. print(g.close())
  50. except ValueError:
  51. print("ValueError")