From a8f0226c8beec6b4d9dc9714c338404da53d7006 Mon Sep 17 00:00:00 2001 From: Julien Palard Date: Fri, 1 Dec 2023 13:52:28 +0100 Subject: [PATCH] Implement batched from an idea of @YashAgarwal in #85. --- README.md | 11 +++++++++++ pipe.py | 7 +++++++ pyproject.toml | 2 +- tox.ini | 2 +- 4 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 919a6bb..21954c0 100644 --- a/README.md +++ b/README.md @@ -294,6 +294,17 @@ See the `Constructing your own` paragraph below. Alphabetical list of available pipes; when several names are listed for a given pipe, these are aliases. +## `batched` + +Like Python 3.12 `itertool.batched`: + +```python +>>> from pipe import batched +>>> list("ABCDEFG" | batched(3)) +[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)] + +``` + ## `chain` Chain a sequence of iterables: diff --git a/pipe.py b/pipe.py index f6d24ef..0990eb7 100644 --- a/pipe.py +++ b/pipe.py @@ -200,6 +200,13 @@ def transpose(iterable): return list(zip(*iterable)) +@Pipe +def batched(iterable, n): + iterator = iter(iterable) + while batch := tuple(itertools.islice(iterator, n)): + yield batch + + chain = Pipe(itertools.chain.from_iterable) chain_with = Pipe(itertools.chain) islice = Pipe(itertools.islice) diff --git a/pyproject.toml b/pyproject.toml index cee4106..6728b4e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -21,7 +21,7 @@ classifiers = [ "Topic :: Software Development", "Topic :: Software Development :: Libraries :: Python Modules", ] -requires-python = ">= 3.7" +requires-python = ">= 3.8" [project.urls] repository = "https://github.com/JulienPalard/Pipe" diff --git a/tox.ini b/tox.ini index daf7074..ecdc3b6 100644 --- a/tox.ini +++ b/tox.ini @@ -15,7 +15,7 @@ exclude_lines = if __name__ == .__main__.: [tox] -envlist = py3{8,9,10,11,12}, flake8, mypy, black, pylint, coverage +envlist = py3{8,9,10,11,12,13}, flake8, mypy, black, pylint, coverage isolated_build = True [testenv]