-
Notifications
You must be signed in to change notification settings - Fork 7.1k
Feat: Add Pythonic Pipeline pattern using functional composition #461
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
Open
michaelj094
wants to merge
1
commit into
faif:master
from
michaelj094:feat/add-functional-pipeline-pattern
+118
−0
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
98 changes: 98 additions & 0 deletions
patterns/behavioral/pipeline.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| """ | ||
| Pipeline / Functional Pipeline (Pythonic) | ||
|
|
||
| This implements the Pipeline pattern using a functional approach, | ||
| where each stage is a callable transforming an iterable. The goal | ||
| is to demonstrate a Pythonic alternative to class-based pipelines | ||
| using generators and composition. | ||
|
|
||
| TL;DR: | ||
| Build data processing flows by chaining small functions. | ||
| In Python, pipelines are best expressed with callables + iterables | ||
| (often generators), not heavy class hierarchies. | ||
|
|
||
| References: | ||
| - https://martinfowler.com/articles/collection-pipeline/ | ||
| - https://en.wikipedia.org/wiki/Pipeline_(software) | ||
|
|
||
|
|
||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from dataclasses import dataclass | ||
| from typing import Callable, Iterable, Iterator, TypeVar | ||
|
|
||
| T = TypeVar("T") | ||
| U = TypeVar("U") | ||
|
|
||
| # A stage transforms an Iterable[T] into an Iterable[U]. | ||
| Stage = Callable[[Iterable[T]], Iterable[U]] | ||
|
|
||
|
|
||
| def compose(*stages: Stage) -> Stage: | ||
| """Compose stages left-to-right into a single stage.""" | ||
| def _composed(data: Iterable): | ||
| out = data | ||
| for stage in stages: | ||
| out = stage(out) | ||
| return out | ||
| return _composed | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class Pipeline: | ||
| """Convenience wrapper around composed stages.""" | ||
| stages: tuple[Stage, ...] | ||
|
|
||
| def __call__(self, data: Iterable[T]) -> Iterable: | ||
| fn = compose(*self.stages) | ||
| return fn(data) | ||
|
|
||
| def then(self, stage: Stage) -> "Pipeline": | ||
| """Return a new Pipeline with an extra stage appended.""" | ||
| return Pipeline(self.stages + (stage,)) | ||
|
|
||
|
|
||
|
|
||
| def map_stage(fn: Callable[[T], U]) -> Stage: | ||
| """Create a mapping stage.""" | ||
| def _stage(data: Iterable[T]) -> Iterator[U]: | ||
| for item in data: | ||
| yield fn(item) | ||
| return _stage | ||
|
|
||
|
|
||
| def filter_stage(pred: Callable[[T], bool]) -> Stage: | ||
| """Create a filtering stage.""" | ||
| def _stage(data: Iterable[T]) -> Iterator[T]: | ||
| for item in data: | ||
| if pred(item): | ||
| yield item | ||
| return _stage | ||
|
|
||
|
|
||
| def take(n: int) -> Stage: | ||
| """Take the first n items from the stream.""" | ||
| if n < 0: | ||
| raise ValueError("n must be >= 0") | ||
|
|
||
| def _stage(data: Iterable[T]) -> Iterator[T]: | ||
| count = 0 | ||
| for item in data: | ||
| if count >= n: | ||
| break | ||
| yield item | ||
| count += 1 | ||
| return _stage | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| # Example: numbers -> keep evens -> square -> take first 3 | ||
| p = Pipeline(( | ||
| filter_stage(lambda x: x % 2 == 0), | ||
| map_stage(lambda x: x * x), | ||
| take(3), | ||
| )) | ||
|
|
||
| print(list(p(range(100)))) # [0, 4, 16] |
19 changes: 19 additions & 0 deletions
tests/behavioral/test_pipeline.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| from patterns.behavioral.pipeline import Pipeline, filter_stage, map_stage, take | ||
|
|
||
|
|
||
| def test_pipeline_composes_stages_lazily(): | ||
| p = Pipeline(( | ||
| filter_stage(lambda x: x % 2 == 1), | ||
| map_stage(lambda x: x + 10), | ||
| take(4), | ||
| )) | ||
|
|
||
| assert list(p(range(100))) == [11, 13, 15, 17] | ||
|
|
||
|
|
||
| def test_take_rejects_negative(): | ||
| try: | ||
| take(-1) | ||
| assert False, "Expected ValueError" | ||
| except ValueError: | ||
| assert True |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.