Skip to content

Commit

Permalink
ENH: add persistent style
Browse files Browse the repository at this point in the history
Function to generate a default dict with a cycler bound to it.  This
functionality is currently in the documentation as an example.

Closes matplotlib#27
  • Loading branch information
tacaswell committed Jun 5, 2016
1 parent 684fb15 commit 9cd5ebb
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
27 changes: 27 additions & 0 deletions cycler.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@
from itertools import product, cycle
from six.moves import zip, reduce
from operator import mul, add
from collections import defaultdict
import copy

__version__ = '0.10.0'
Expand Down Expand Up @@ -558,3 +559,29 @@ def _cycler(label, itr):
itr = (v[lab] for v in itr)

return Cycler._from_iter(label, itr)


class OutOfStyles(StopIteration):
pass


def persistent_style(cyl, repeat=False):
'''Create a defaultdict mapping keys -> styles
Parameters
----------
cyl : Cycler
The c
'''
def next_style():
try:
next(cy_iter)
except StopIteration:
raise OutOfStyles()

if repeat:
cy_iter = cyl()
return defaultdict(lambda: next(cy_iter))
else:
cy_iter = iter(cyl)
return defaultdict(next_style)
23 changes: 22 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, persistent_style, OutOfStyles
import pytest
from itertools import product, cycle, chain
from operator import add, iadd, mul, imul
Expand Down Expand Up @@ -341,3 +341,24 @@ def test_contains():

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


@pytest.mark.parametrize('repeat', [True, False])
def test_persistent(repeat):
a = cycler('a', range(3)) + cycler('b', range(3))
dd = persistent_style(a, repeat=repeat)
one = dd['one']
two = dd['two']
three = dd['three']

assert one == dd['one']
assert two == dd['two']
assert three == dd['three']
if not repeat:
with pytest.raises(OutOfStyles):
dd['four']
else:
assert one == dd['four']
assert one == dd['four']
assert two == dd['five']
assert three == dd['six']

0 comments on commit 9cd5ebb

Please sign in to comment.