This repository has been archived by the owner on Jan 2, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 32
/
iterator.py
71 lines (51 loc) · 1.53 KB
/
iterator.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
62
63
64
65
66
67
68
69
70
71
"""Iterator pattern
"""
class MyIterator(object):
def __init__(self, *args):
self.data = args
self.index = 0
def __iter__(self):
generator = self.generator_function()
return generator
def __next__(self):
if len(self.data) > self.index:
obj = self.data[self.index]
self.index += 1
else:
raise StopIteration("No more elements!")
return obj
def __getitem__(self, index):
return self.data[index]
def __len__(self):
return len(self.data[self.index :])
def generator_function(self):
for d in self.data[self.index :]:
self.index += 1
yield "Item: {} (type: {})".format(d, type(d))
def some_function(a, b, c=123):
print(a, b, c)
def main():
iterator = MyIterator(1, 3.0, None, "hello", some_function)
print("Initial length")
print(len(iterator))
index = 3
print("\nGet item at index {}".format(index))
print(iterator[index])
print("\n__next__ calls")
print(next(iterator))
print(next(iterator))
print("\nLength after __next__ calls")
print(len(iterator))
print("\nFor loop with the remaining items")
for item in iterator:
print(item)
print("\nStopIteration")
try:
next(iterator)
except StopIteration as e:
print(e)
print("But in Python we don't really need any of the above...")
for item in (1, 3.0, None, "hello", some_function):
print(item)
if __name__ == "__main__":
main()