Skip to content

Commit 78ab830

Browse files
committed
ENH: make Cycler callable to return infinite cycle
Following in the tradition of generators and co-routines, to get an infinite cycle call the `Cycler` object.
1 parent 6543704 commit 78ab830

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

cycler.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
unicode_literals)
33

44
import six
5-
from itertools import product
5+
from itertools import product, cycle
66
from six.moves import zip, reduce
77
from operator import mul, add
88
import copy
@@ -62,6 +62,9 @@ class Cycler(object):
6262
Function which composes the 'left' and 'right' cyclers.
6363
6464
"""
65+
def __call__(self):
66+
return cycle(self)
67+
6568
def __init__(self, left, right=None, op=None):
6669
"""Semi-private init
6770

doc/source/index.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,16 @@ which returns a new `Cycler` with a new label, but the same values.
6969
cycler('ec', color_cycle)
7070
7171
72+
Iterating over a `Cycler` results in the finite list of entries, to
73+
get an infinite cycle, call the `Cycler` object (a-la a generator)
74+
75+
.. ipython:: python
76+
77+
cc = color_cycle()
78+
for j, c in zip(range(5), cc):
79+
print(j, c)
80+
81+
7282
Composition
7383
-----------
7484

test_cycler.py

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,8 @@
33
import six
44
from six.moves import zip, range
55
from cycler import cycler, Cycler
6-
from nose.tools import assert_equal, assert_raises
7-
from itertools import product
6+
from nose.tools import assert_equal, assert_raises, assert_true
7+
from itertools import product, cycle
88
from operator import add, iadd, mul, imul
99

1010

@@ -148,3 +148,15 @@ def test_repr():
148148

149149
yield _repr_tester_helper, '_repr_html_', c + c2, sum_html
150150
yield _repr_tester_helper, '_repr_html_', c * c2, prod_html
151+
152+
153+
def test_call():
154+
c = cycler('c', 'rgb')
155+
c_cycle = c()
156+
assert_true(isinstance(c_cycle, cycle))
157+
j = 0
158+
for a, b in zip(2*c, c_cycle):
159+
j += 1
160+
assert_equal(a, b)
161+
162+
assert_equal(j, len(c) * 2)

0 commit comments

Comments
 (0)