Skip to content

Commit 68a3b1c

Browse files
committed
Introduced an experimental Stream API
1 parent 1a9075f commit 68a3b1c

File tree

4 files changed

+83
-4
lines changed

4 files changed

+83
-4
lines changed

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[project]
22
name = "readables-py"
3-
version = "0.1.7"
3+
version = "0.2.0"
44
description = "Add readability and self-documentation to Python code"
55
requires-python = ">=3.9"
66
dependencies = []

readables/stream/__init__.py

Whitespace-only changes.

readables/stream/sync.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
from typing import Iterable, Any, Generic, TypeVar, Callable, List, Iterator, Generator
2+
3+
T = TypeVar('T')
4+
S = TypeVar('S')
5+
R = TypeVar('R')
6+
7+
8+
class Filter(Generic[T]):
9+
def __init__(self, fn: Callable[[T], bool]):
10+
self._fn = fn
11+
12+
def __call__(self, t: T):
13+
return self._fn(t)
14+
15+
16+
class Map(Generic[S, R]):
17+
def __init__(self, fn: Callable[[S], R]):
18+
self._fn = fn
19+
20+
def __call__(self, s: S) -> R:
21+
return self._fn(s)
22+
23+
24+
class FlatMap(Generic[S, R]):
25+
"""
26+
Flat map an iterable object
27+
28+
While code is identical to Map, how it is used is different.
29+
"""
30+
def __init__(self, fn: Callable[[S], R]):
31+
self._fn = fn
32+
33+
def __call__(self, s: S) -> Generator[R, Any, None]:
34+
yield self._fn(s)
35+
36+
37+
class Stream(Generic[T, S]):
38+
def __init__(self, source: Iterator[T]):
39+
self._source = source
40+
self._chain: List[Filter | Map | FlatMap] = []
41+
42+
def observe(self):
43+
for item in self._source:
44+
included = True
45+
iterated_value = item
46+
47+
for act in self._chain:
48+
if isinstance(act, Filter) and not act(iterated_value):
49+
included = False
50+
break
51+
52+
if isinstance(act, Map):
53+
iterated_value = act(iterated_value)
54+
55+
if isinstance(act, FlatMap):
56+
raise NotImplementedError('To be implemented')
57+
58+
if not included:
59+
continue
60+
61+
yield iterated_value

uv.lock

Lines changed: 21 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)