gen_yield_from_throw3.py 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. # yield-from a user-defined generator with a throw() method
  2. class Iter:
  3. def __iter__(self):
  4. return self
  5. def __next__(self):
  6. return 1
  7. def throw(self, x):
  8. print('throw', x)
  9. return 456
  10. def gen():
  11. yield from Iter()
  12. # calling close() should not call throw()
  13. g = gen()
  14. print(next(g))
  15. g.close()
  16. # can throw a non-exception object
  17. g = gen()
  18. print(next(g))
  19. print(g.throw(123))
  20. # throwing an exception class just injects that class
  21. g = gen()
  22. print(next(g))
  23. print(g.throw(ZeroDivisionError))
  24. # this user-defined generator doesn't have a throw() method
  25. class Iter2:
  26. def __iter__(self):
  27. return self
  28. def __next__(self):
  29. return 1
  30. def gen2():
  31. yield from Iter2()
  32. # the thrown ValueError is not intercepted by the user class
  33. g = gen2()
  34. print(next(g))
  35. try:
  36. g.throw(ValueError)
  37. except:
  38. print('ValueError')
  39. # the thrown 123 is not an exception so raises a TypeError
  40. g = gen2()
  41. print(next(g))
  42. try:
  43. g.throw(123)
  44. except TypeError:
  45. print('TypeError')