| 1 | #!/usr/bin/env python2
|
| 2 | """
|
| 3 | iterators.py: Simple iterators
|
| 4 | """
|
| 5 | from __future__ import print_function
|
| 6 |
|
| 7 | import os
|
| 8 |
|
| 9 | from mycpp import mylib
|
| 10 | from mycpp.mylib import log, iteritems
|
| 11 |
|
| 12 | from typing import Iterator, Tuple
|
| 13 |
|
| 14 |
|
| 15 | def 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 |
|
| 21 | def f(n):
|
| 22 | # type: (int) -> Iterator[int]
|
| 23 | for i in xrange(0, n):
|
| 24 | yield i
|
| 25 |
|
| 26 |
|
| 27 | class 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 |
|
| 48 | def 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 |
|
| 91 | def run_benchmarks():
|
| 92 | # type: () -> None
|
| 93 | pass
|
| 94 |
|
| 95 |
|
| 96 | if __name__ == '__main__':
|
| 97 | if os.getenv('BENCHMARK'):
|
| 98 | log('Benchmarking...')
|
| 99 | run_benchmarks()
|
| 100 | else:
|
| 101 | run_tests()
|