OILS / mycpp / examples / test_iterators.py View on Github | oilshell.org

101 lines, 65 significant
1#!/usr/bin/env python2
2"""
3iterators.py: Simple iterators
4"""
5from __future__ import print_function
6
7import os
8
9from mycpp import mylib
10from mycpp.mylib import log, iteritems
11
12from typing import Iterator, Tuple
13
14
15def g(n):
16 # type: (int) -> Iterator[Tuple[int, str]]
17 for i in f(n):
18 yield (i, '2 * %d = %d' % (i, 2 * i))
19
20
21def f(n):
22 # type: (int) -> Iterator[int]
23 for i in xrange(0, n):
24 yield i
25
26
27class Foo(object):
28
29 def __init__(self):
30 # type: () -> None
31 pass
32
33 def bar(self, n):
34 # type: (int) -> Iterator[int]
35 for i in xrange(0, n):
36 yield i
37
38 def baz(self, n):
39 # type: (int) -> Iterator[Tuple[int, str]]
40 it_g = g(n)
41 while True:
42 try:
43 yield it_g.next()
44 except StopIteration:
45 break
46
47
48def run_tests():
49 # type: () -> None
50 log('--- simple iterators')
51 for i in f(3):
52 log("f() gave %d", i)
53
54 foo = Foo()
55 for i in foo.bar(4):
56 log("Foo.bar() gave %d", i)
57
58 log('--- nested iterators')
59 for i, s in g(3):
60 log("g() gave (%d, %r)", i, s)
61
62 for i, s in foo.baz(3):
63 log("Foo.baz() gave (%d, %r)", i, s)
64
65 for i in f(3):
66 for j in f(3):
67 log("f() gave %d, %d", i, j)
68
69 log('--- iterator assignment')
70 it_f = f(5)
71 while True:
72 try:
73 log("next(f()) gave %d", it_f.next())
74 except StopIteration:
75 break
76
77 it_g = g(5)
78 while True:
79 try:
80 i, s = it_g.next()
81 log("next(g()) gave (%d, %r)", i, s)
82 except StopIteration:
83 break
84
85 it = f(5)
86 l = list(it)
87 for i, x in enumerate(l):
88 log("l[%d] = %d", i, x)
89
90
91def run_benchmarks():
92 # type: () -> None
93 pass
94
95
96if __name__ == '__main__':
97 if os.getenv('BENCHMARK'):
98 log('Benchmarking...')
99 run_benchmarks()
100 else:
101 run_tests()