Skip to content

Commit

Permalink
ENH: cycler with a tail
Browse files Browse the repository at this point in the history
Add a generator function to add an infinite 'tail' onto a cycler.

Closes matplotlib#30
  • Loading branch information
tacaswell committed Jun 5, 2016
1 parent 684fb15 commit 89b7d3f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
29 changes: 29 additions & 0 deletions cycler.py
Original file line number Diff line number Diff line change
Expand Up @@ -558,3 +558,32 @@ def _cycler(label, itr):
itr = (v[lab] for v in itr)

return Cycler._from_iter(label, itr)


def cycler_with_tail(cyl, tail):
'''After the cycle is exhausted continue to yield tail
Parameters
----------
cyl : Cycler
The cycler to iterate through
tail : dict
The dictionary to yield. Must have the same keys as ``cyl``.
Yields
------
sty : dict
'''
tk = set(tail.keys())
if cyl.keys != tk:
raise RuntimeError('The cycler has keys {} and the tail {}. The '
'different keys are {}'.format(cyl.keys,
tk, tk ^ cyl.keys))

for sty in cyl:
yield sty

while True:
yield tail
17 changes: 16 additions & 1 deletion test_cycler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

import six
from six.moves import zip, range
from cycler import cycler, Cycler, concat
from cycler import cycler, Cycler, concat, cycler_with_tail
import pytest
from itertools import product, cycle, chain
from operator import add, iadd, mul, imul
Expand Down Expand Up @@ -341,3 +341,18 @@ def test_contains():

assert 'a' in ab
assert 'b' in ab


def test_tail():
a = cycler('a', range(3))
tail = {'a': 4}

cy_with_tail = cycler_with_tail(a, tail)
for j in range(3):
next(cy_with_tail)

for j in range(5):
assert {'a': 4} == next(cy_with_tail)

with pytest.raises(RuntimeError):
next(cycler_with_tail(a, {'b': 1}))

0 comments on commit 89b7d3f

Please sign in to comment.