Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enh persistent style dictionary #38

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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']