forked from faif/python-patterns
-
Notifications
You must be signed in to change notification settings - Fork 0
/
iterator_alt.py
61 lines (46 loc) · 1.21 KB
/
iterator_alt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
"""
Implementation of the iterator pattern using the iterator protocol from Python
*TL;DR
Traverses a container and accesses the container's elements.
"""
from __future__ import annotations
class NumberWords:
"""Counts by word numbers, up to a maximum of five"""
_WORD_MAP = (
"one",
"two",
"three",
"four",
"five",
)
def __init__(self, start: int, stop: int) -> None:
self.start = start
self.stop = stop
def __iter__(self) -> NumberWords: # this makes the class an Iterable
return self
def __next__(self) -> str: # this makes the class an Iterator
if self.start > self.stop or self.start > len(self._WORD_MAP):
raise StopIteration
current = self.start
self.start += 1
return self._WORD_MAP[current - 1]
# Test the iterator
def main():
"""
# Counting to two...
>>> for number in NumberWords(start=1, stop=2):
... print(number)
one
two
# Counting to five...
>>> for number in NumberWords(start=1, stop=5):
... print(number)
one
two
three
four
five
"""
if __name__ == "__main__":
import doctest
doctest.testmod()