iter1.py 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. # test user defined iterators
  2. # this class is not iterable
  3. class NotIterable:
  4. pass
  5. try:
  6. for i in NotIterable():
  7. pass
  8. except TypeError:
  9. print('TypeError')
  10. # this class has no __next__ implementation
  11. class NotIterable:
  12. def __iter__(self):
  13. return self
  14. try:
  15. print(all(NotIterable()))
  16. except TypeError:
  17. print('TypeError')
  18. class MyStopIteration(StopIteration):
  19. pass
  20. class myiter:
  21. def __init__(self, i):
  22. self.i = i
  23. def __iter__(self):
  24. return self
  25. def __next__(self):
  26. if self.i <= 0:
  27. # stop in the usual way
  28. raise StopIteration
  29. elif self.i == 10:
  30. # stop with an argument
  31. raise StopIteration(42)
  32. elif self.i == 20:
  33. # raise a non-stop exception
  34. raise TypeError
  35. elif self.i == 30:
  36. # raise a user-defined stop iteration
  37. print('raising MyStopIteration')
  38. raise MyStopIteration
  39. else:
  40. # return the next value
  41. self.i -= 1
  42. return self.i
  43. for i in myiter(5):
  44. print(i)
  45. for i in myiter(12):
  46. print(i)
  47. try:
  48. for i in myiter(22):
  49. print(i)
  50. except TypeError:
  51. print('raised TypeError')
  52. try:
  53. for i in myiter(5):
  54. print(i)
  55. raise StopIteration
  56. except StopIteration:
  57. print('raised StopIteration')
  58. for i in myiter(32):
  59. print(i)
  60. # repeat some of the above tests but use tuple() to walk the iterator (tests mp_iternext)
  61. print(tuple(myiter(5)))
  62. print(tuple(myiter(12)))
  63. print(tuple(myiter(32)))
  64. try:
  65. tuple(myiter(22))
  66. except TypeError:
  67. print('raised TypeError')