Skip to content

Commit 0a41f2b

Browse files
committed
Add the intersperse utility procedure
1 parent b930beb commit 0a41f2b

1 file changed

Lines changed: 16 additions & 0 deletions

File tree

src/csspring/utils.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,22 @@
1515
T_co = TypeVar('T_co', covariant=True)
1616
T_contra = TypeVar('T_contra', contravariant=True)
1717

18+
def intersperse(*items: T, separator: T) -> Iterable[T]:
19+
"""Yield items with a separator yielded between each item.
20+
21+
E.g. `intersperse(("foo", "bar", "baz"), "-")` will yield "foo", "-", "bar", "-", then "baz".
22+
23+
Owing to a mere design choice, this procedure demands, by the type checker, that the separator be of a type co-variant with the type of items in the sequence, with the latter assumed to be homogenous (items are all of the same type).
24+
25+
:param items: A sequence (items are assumed to be of the same type or share a super-type)
26+
:param separator: A value to yield between yielding each item in the sequence
27+
"""
28+
it = iter(items)
29+
yield next(it)
30+
for item in it:
31+
yield separator
32+
yield item
33+
1834
@runtime_checkable
1935
class Reader(Protocol[T_co]):
2036
"""An interface to readable/readers, to assist type checking for the most part."""

0 commit comments

Comments
 (0)