Skip to content

Commit ae50f6e

Browse files
committed
ENH: add concat
Adds a top level function `concat` and a `Cycler` method `concat` which will concatenate two cyclers. The method can be chained. closes #1
1 parent 1f3e5c4 commit ae50f6e

File tree

2 files changed

+53
-2
lines changed

2 files changed

+53
-2
lines changed

cycler.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,41 @@ def simplify(self):
389389
trans = self._transpose()
390390
return reduce(add, (_cycler(k, v) for k, v in six.iteritems(trans)))
391391

392+
def concat(self, other):
393+
return concat(self, other)
394+
395+
396+
def concat(left, right):
397+
"""Concatenate two cyclers.
398+
399+
The keys must match exactly.
400+
401+
This returns a single Cycler which is equivalent to
402+
`itertools.chain(left, right)`
403+
404+
Parameters
405+
----------
406+
left, right : `Cycler`
407+
The two `Cycler` instances to concatenate
408+
409+
Returns
410+
-------
411+
ret : `Cycler`
412+
The concatenated `Cycler`
413+
"""
414+
if left.keys != right.keys:
415+
msg = '\n\t'.join(["Keys do not match:",
416+
"Intersection: {both!r}",
417+
"Disjoint: {just_one!r}"
418+
]).format(
419+
both=left.keys&right.keys,
420+
just_one=left.keys^right.keys)
421+
422+
raise ValueError(msg)
423+
424+
_l = left._transpose()
425+
_r = right._transpose()
426+
return reduce(add, (_cycler(k, _l[k] + _r[k]) for k in left.keys))
392427

393428
def cycler(*args, **kwargs):
394429
"""

test_cycler.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,10 @@
22

33
import six
44
from six.moves import zip, range
5-
from cycler import cycler, Cycler
5+
from cycler import cycler, Cycler, concat
66
from nose.tools import (assert_equal, assert_not_equal,
77
assert_raises, assert_true)
8-
from itertools import product, cycle
8+
from itertools import product, cycle, chain
99
from operator import add, iadd, mul, imul
1010

1111

@@ -279,3 +279,19 @@ def test_starange_init():
279279
c2 = cycler('lw', range(3))
280280
cy = Cycler(list(c), list(c2), zip)
281281
assert_equal(cy, c + c2)
282+
283+
284+
def test_concat():
285+
a = cycler('a', range(3))
286+
for con, chn in zip(a.concat(a), chain(a, a)):
287+
assert_equal(con, chn)
288+
289+
for con, chn in zip(concat(a, a), chain(a, a)):
290+
assert_equal(con, chn)
291+
292+
293+
def test_concat_fail():
294+
a = cycler('a', range(3))
295+
b = cycler('b', range(3))
296+
assert_raises(ValueError, concat, a, b)
297+
assert_raises(ValueError, a.concat, b)

0 commit comments

Comments
 (0)