pyfun-zeromode 0.1.0__tar.gz → 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,184 @@
1
+ Metadata-Version: 2.4
2
+ Name: pyfun-zeromode
3
+ Version: 1.0.0
4
+ Summary: Functional programming constructs (Maybe, Pipe) for Python
5
+ Author: Avilay Parekh
6
+ Author-email: Avilay Parekh <avilay@gmail.com>
7
+ License-Expression: MIT
8
+ Requires-Dist: fire>=0.7.1
9
+ Requires-Python: >=3.14
10
+ Project-URL: Repository, https://github.com/avilay/pyfun
11
+ Description-Content-Type: text/markdown
12
+
13
+ # PyFun Design Doc
14
+
15
+ PyFun implements the [`Monad`](https://wiki.haskell.org/Monad) typeclass from Haskell in Python. Because Python does not have higher-kinded types, I cannot implement the Monad functions for all types. For this reason PyFun also implements the [`Maybe`](https://wiki.haskell.org/Maybe) type in Python, and implements Monad functions on this type.
16
+
17
+ Here is some non-standard terminology that I use in this design doc to make things unambiguous:
18
+ * **raw**: This is used to indicate a value that is not inside a `Maybe`. When used in context of functions, it indicates a function that takes in raw values and returns raw values.
19
+ * **wrapped**: This is used to indicate a value that is inside a `Maybe`, it could be `None` or have an actual value. We don't know that at compile time. When used in context of functions, it means a function that takes in a wrapped value and returns a wrapped value.
20
+ * **partially-wrapped**: This is only used in context of a function, where the function either takes in a raw value and returns a wrapped value, or takes in a wrapped value and returns a raw value. It will be clear from context which of these I mean.
21
+
22
+ ## Main Functions
23
+
24
+ * `map`: This is a higher-order function that takes in a wrapped value and applies a raw function to it.
25
+ * `bind`
26
+ * `then`
27
+
28
+ There is no point implementing `pure` for a single type, so it is omitted. I have also omitted `<*>` because there are simpler ways to achieve what it does by using the `match` statement.
29
+
30
+ ## Helper Functions
31
+
32
+ * `maybe`: Converts a value to `Some[T]` or `Nothing` depending on whether it exists or is `None`.
33
+ * `value_or`: Unwraps the `Maybe` value if it exists otherwise returns the default passed in with this function.
34
+ * `to_optional`: Unwraps the `Maybe` value if it exists, otherwise returns `None`.
35
+
36
+ ## Use Cases
37
+
38
+ These use cases use the following three helper functions:
39
+
40
+ * `lookup(mapping: dict[K, V], key: K) → Maybe[V]`: Returns the wrapped value if `key` exists, otherwise `Nothing`.
41
+ * `parse_int(raw: str) → Maybe[int]`: Returns wrapped integer if `raw` can be parsed, otherwise `Nothing`.
42
+ * `ensure(condition: Bool) → Maybe[None]`: Returns `Some(None)` if `condition` is `True`, otherwise `Nothing.
43
+
44
+ #### 1. Normalize an optional field
45
+
46
+ We have a dictionary `profile` which may or may not contain the `email` field. If it does, we want to normalize it.
47
+
48
+ ```python
49
+ profile = {
50
+ "email": " COOKIE@Monster.com ",
51
+ "name": "Cookie Monster",
52
+ "last_activity_at": "2026-10-01T22:54:14.627670"
53
+ }
54
+ ```
55
+
56
+ Without PyFun:
57
+
58
+ ```python
59
+ # Without PyFun
60
+ email = profile.get("email")
61
+ if email is not None:
62
+ email = email.strip().lower()
63
+
64
+ # With PyFun
65
+ email = lookup(profile, "email").map(str.strip).map(str.lower)
66
+
67
+ # email is "cookie@monster.com" or None/Nothing
68
+ ```
69
+
70
+ #### 2. Process an optional field
71
+
72
+ Calculate whether this is a DAU user or a MAU user, but only if the "last_activity_at" field is present.
73
+
74
+ ```python
75
+ # Without PyFun
76
+ activity_at = profile.get("last_activity_at")
77
+ delta = (date.today() - datetime.fromisoformat(activity_at).date()).days if activity_at else None
78
+ if delta is not None:
79
+ dau, mau = update_metric(delta)
80
+
81
+ # With PyFun
82
+ dau, mau = lookup(profile, "last_activity_at")
83
+ .map(datetime.fromisoformat)
84
+ .map(date)
85
+ .map(lambda dt: (date.today() - dt).days)
86
+ .map(update_metric)
87
+ .unwrap()
88
+
89
+ # OR
90
+ dau, mau = lookup(profile, "last_activity_at")
91
+ .map(lambda dt: (date.today() - datetime.fromisoformat(dt).date()).days)
92
+ .map(update_metric)
93
+ .unwrap()
94
+ ```
95
+
96
+ #### 3. Parse then Validate
97
+
98
+ ```python
99
+ # Without PyFun
100
+ # parse_int :: str -> int | None
101
+ # valid_port :: int -> int | None
102
+ port: int | None = None
103
+ if (requested_port := parse_int("8080")) is not None:
104
+ port = valid_port()
105
+
106
+ # With PyFun
107
+ # parse_int :: str -> Maybe[int]
108
+ # valid_port :: int -> Maybe[int]
109
+ port = parse_int("8080").bind(valid_port)
110
+ ```
111
+
112
+ #### 4. Walk nested data where any level might be missing
113
+
114
+ ```python
115
+ # Without PyFun
116
+ # lookup :: (Iterable[User], int) -> User | None
117
+ # get_address :: User -> Address | None
118
+ # get_city :: Address -> City | None
119
+ city: City | None = None
120
+ if (user := lookup(users, 1)) is not None and (addr := get_address(user)) is not None:
121
+ city = get_city(addr)
122
+
123
+ # With PyFun
124
+ # lookup :: (Iterable[User], int) -> Maybe[User]
125
+ # get_address :: User -> Maybe[Address]
126
+ # get_city :: Address -> Maybe[City]
127
+ city = lookup(users, 1).bind(get_address).bind(get_city)
128
+ ```
129
+
130
+ #### 5. A later step needs an earlier value
131
+
132
+ ```python
133
+ # Without PyFun
134
+ # checked_div :: (int, int) -> int | None
135
+ speed: float | None = None
136
+ if (d := parse_int(distance)) is not None and (h := parse_int(hours)) is not None:
137
+ speed = checked_div(d, h)
138
+
139
+ # With PyFun
140
+ # checked_div :: (int, int) -> Maybe[float]
141
+ speed = parse_int(distance).bind(lambda d: parse_int(hours).bind(lambda h: checked_div(d, h)))
142
+
143
+ # OR
144
+ def speed(distance: str, hours: str) -> Maybe[float]:
145
+ match parse_int(distance), parse_int(hours):
146
+ case Some(d), Some(h):
147
+ return checked_div(d, h)
148
+ case _:
149
+ return Nothing()
150
+ ```
151
+
152
+ #### 6. Guard a computation with preconditions
153
+
154
+ ```python
155
+ # Without PyFun
156
+ newbal: int | None = None
157
+ if amount > 0 and amount <= balance:
158
+ newbal = balance - amount
159
+
160
+ # With PyFun
161
+ newbal = ensure(amount > 0)
162
+ .then(lambda: ensure(amount <= balance))
163
+ .then(lambda: Some(balance - amount))
164
+ ```
165
+
166
+ #### 7. Stop at the first failure
167
+
168
+ ```python
169
+ # Without PyFun
170
+ # validate :: () -> Bool
171
+ # connect :: () -> Connection | None
172
+ # fetch :: Connection -> Cookie
173
+ cookie: Cookie | None = None
174
+ if validate():
175
+ if (conn := connect()):
176
+ cookie = fetch(conn)
177
+
178
+ # With PyFun
179
+ # validate :: () -> Maybe[None]
180
+ # connect :: () -> Maybe[Connection]
181
+ # fetch :: Connection -> Cookie
182
+ cookie = validate().then(connect).bind(fetch)
183
+ ```
184
+
@@ -0,0 +1,172 @@
1
+ # PyFun Design Doc
2
+
3
+ PyFun implements the [`Monad`](https://wiki.haskell.org/Monad) typeclass from Haskell in Python. Because Python does not have higher-kinded types, I cannot implement the Monad functions for all types. For this reason PyFun also implements the [`Maybe`](https://wiki.haskell.org/Maybe) type in Python, and implements Monad functions on this type.
4
+
5
+ Here is some non-standard terminology that I use in this design doc to make things unambiguous:
6
+ * **raw**: This is used to indicate a value that is not inside a `Maybe`. When used in context of functions, it indicates a function that takes in raw values and returns raw values.
7
+ * **wrapped**: This is used to indicate a value that is inside a `Maybe`, it could be `None` or have an actual value. We don't know that at compile time. When used in context of functions, it means a function that takes in a wrapped value and returns a wrapped value.
8
+ * **partially-wrapped**: This is only used in context of a function, where the function either takes in a raw value and returns a wrapped value, or takes in a wrapped value and returns a raw value. It will be clear from context which of these I mean.
9
+
10
+ ## Main Functions
11
+
12
+ * `map`: This is a higher-order function that takes in a wrapped value and applies a raw function to it.
13
+ * `bind`
14
+ * `then`
15
+
16
+ There is no point implementing `pure` for a single type, so it is omitted. I have also omitted `<*>` because there are simpler ways to achieve what it does by using the `match` statement.
17
+
18
+ ## Helper Functions
19
+
20
+ * `maybe`: Converts a value to `Some[T]` or `Nothing` depending on whether it exists or is `None`.
21
+ * `value_or`: Unwraps the `Maybe` value if it exists otherwise returns the default passed in with this function.
22
+ * `to_optional`: Unwraps the `Maybe` value if it exists, otherwise returns `None`.
23
+
24
+ ## Use Cases
25
+
26
+ These use cases use the following three helper functions:
27
+
28
+ * `lookup(mapping: dict[K, V], key: K) → Maybe[V]`: Returns the wrapped value if `key` exists, otherwise `Nothing`.
29
+ * `parse_int(raw: str) → Maybe[int]`: Returns wrapped integer if `raw` can be parsed, otherwise `Nothing`.
30
+ * `ensure(condition: Bool) → Maybe[None]`: Returns `Some(None)` if `condition` is `True`, otherwise `Nothing.
31
+
32
+ #### 1. Normalize an optional field
33
+
34
+ We have a dictionary `profile` which may or may not contain the `email` field. If it does, we want to normalize it.
35
+
36
+ ```python
37
+ profile = {
38
+ "email": " COOKIE@Monster.com ",
39
+ "name": "Cookie Monster",
40
+ "last_activity_at": "2026-10-01T22:54:14.627670"
41
+ }
42
+ ```
43
+
44
+ Without PyFun:
45
+
46
+ ```python
47
+ # Without PyFun
48
+ email = profile.get("email")
49
+ if email is not None:
50
+ email = email.strip().lower()
51
+
52
+ # With PyFun
53
+ email = lookup(profile, "email").map(str.strip).map(str.lower)
54
+
55
+ # email is "cookie@monster.com" or None/Nothing
56
+ ```
57
+
58
+ #### 2. Process an optional field
59
+
60
+ Calculate whether this is a DAU user or a MAU user, but only if the "last_activity_at" field is present.
61
+
62
+ ```python
63
+ # Without PyFun
64
+ activity_at = profile.get("last_activity_at")
65
+ delta = (date.today() - datetime.fromisoformat(activity_at).date()).days if activity_at else None
66
+ if delta is not None:
67
+ dau, mau = update_metric(delta)
68
+
69
+ # With PyFun
70
+ dau, mau = lookup(profile, "last_activity_at")
71
+ .map(datetime.fromisoformat)
72
+ .map(date)
73
+ .map(lambda dt: (date.today() - dt).days)
74
+ .map(update_metric)
75
+ .unwrap()
76
+
77
+ # OR
78
+ dau, mau = lookup(profile, "last_activity_at")
79
+ .map(lambda dt: (date.today() - datetime.fromisoformat(dt).date()).days)
80
+ .map(update_metric)
81
+ .unwrap()
82
+ ```
83
+
84
+ #### 3. Parse then Validate
85
+
86
+ ```python
87
+ # Without PyFun
88
+ # parse_int :: str -> int | None
89
+ # valid_port :: int -> int | None
90
+ port: int | None = None
91
+ if (requested_port := parse_int("8080")) is not None:
92
+ port = valid_port()
93
+
94
+ # With PyFun
95
+ # parse_int :: str -> Maybe[int]
96
+ # valid_port :: int -> Maybe[int]
97
+ port = parse_int("8080").bind(valid_port)
98
+ ```
99
+
100
+ #### 4. Walk nested data where any level might be missing
101
+
102
+ ```python
103
+ # Without PyFun
104
+ # lookup :: (Iterable[User], int) -> User | None
105
+ # get_address :: User -> Address | None
106
+ # get_city :: Address -> City | None
107
+ city: City | None = None
108
+ if (user := lookup(users, 1)) is not None and (addr := get_address(user)) is not None:
109
+ city = get_city(addr)
110
+
111
+ # With PyFun
112
+ # lookup :: (Iterable[User], int) -> Maybe[User]
113
+ # get_address :: User -> Maybe[Address]
114
+ # get_city :: Address -> Maybe[City]
115
+ city = lookup(users, 1).bind(get_address).bind(get_city)
116
+ ```
117
+
118
+ #### 5. A later step needs an earlier value
119
+
120
+ ```python
121
+ # Without PyFun
122
+ # checked_div :: (int, int) -> int | None
123
+ speed: float | None = None
124
+ if (d := parse_int(distance)) is not None and (h := parse_int(hours)) is not None:
125
+ speed = checked_div(d, h)
126
+
127
+ # With PyFun
128
+ # checked_div :: (int, int) -> Maybe[float]
129
+ speed = parse_int(distance).bind(lambda d: parse_int(hours).bind(lambda h: checked_div(d, h)))
130
+
131
+ # OR
132
+ def speed(distance: str, hours: str) -> Maybe[float]:
133
+ match parse_int(distance), parse_int(hours):
134
+ case Some(d), Some(h):
135
+ return checked_div(d, h)
136
+ case _:
137
+ return Nothing()
138
+ ```
139
+
140
+ #### 6. Guard a computation with preconditions
141
+
142
+ ```python
143
+ # Without PyFun
144
+ newbal: int | None = None
145
+ if amount > 0 and amount <= balance:
146
+ newbal = balance - amount
147
+
148
+ # With PyFun
149
+ newbal = ensure(amount > 0)
150
+ .then(lambda: ensure(amount <= balance))
151
+ .then(lambda: Some(balance - amount))
152
+ ```
153
+
154
+ #### 7. Stop at the first failure
155
+
156
+ ```python
157
+ # Without PyFun
158
+ # validate :: () -> Bool
159
+ # connect :: () -> Connection | None
160
+ # fetch :: Connection -> Cookie
161
+ cookie: Cookie | None = None
162
+ if validate():
163
+ if (conn := connect()):
164
+ cookie = fetch(conn)
165
+
166
+ # With PyFun
167
+ # validate :: () -> Maybe[None]
168
+ # connect :: () -> Maybe[Connection]
169
+ # fetch :: Connection -> Cookie
170
+ cookie = validate().then(connect).bind(fetch)
171
+ ```
172
+
@@ -0,0 +1,22 @@
1
+ [project]
2
+ name = "pyfun-zeromode"
3
+ version = "1.0.0"
4
+ description = "Functional programming constructs (Maybe, Pipe) for Python"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ requires-python = ">=3.14"
8
+ dependencies = ["fire>=0.7.1"]
9
+
10
+ [[project.authors]]
11
+ name = "Avilay Parekh"
12
+ email = "avilay@gmail.com"
13
+
14
+ [project.urls]
15
+ Repository = "https://github.com/avilay/pyfun"
16
+
17
+ [build-system]
18
+ requires = ["uv_build>=0.9.26,<0.10.0"]
19
+ build-backend = "uv_build"
20
+
21
+ [tool.uv.build-backend]
22
+ module-name = "pyfun"
@@ -1,17 +1,23 @@
1
1
  [project]
2
2
  name = "pyfun-zeromode"
3
- version = "0.1.0"
4
- description = "Add your description here"
3
+ version = "1.0.0"
4
+ description = "Functional programming constructs (Maybe, Pipe) for Python"
5
5
  readme = "README.md"
6
+ license = "MIT"
6
7
  authors = [
7
8
  { name = "Avilay Parekh", email = "avilay@gmail.com" }
8
9
  ]
9
10
  requires-python = ">=3.14"
10
- dependencies = []
11
+ dependencies = [
12
+ "fire>=0.7.1",
13
+ ]
14
+
15
+ [project.urls]
16
+ Repository = "https://github.com/avilay/pyfun"
11
17
 
12
18
  [build-system]
13
19
  requires = ["uv_build>=0.9.26,<0.10.0"]
14
20
  build-backend = "uv_build"
15
21
 
16
22
  [tool.uv.build-backend]
17
- module-name = "pyfun"
23
+ module-name = "pyfun"
@@ -0,0 +1,4 @@
1
+ from pyfun.maybe import Maybe, Nothing, Some, ensure, maybe
2
+ from pyfun.pipe import Pipe
3
+
4
+ __all__ = ["Maybe", "Nothing", "Some", "maybe", "ensure", "Pipe"]
@@ -0,0 +1,51 @@
1
+ from dataclasses import dataclass
2
+ from typing import Callable
3
+
4
+
5
+ @dataclass(frozen=True, slots=True)
6
+ class Some[T]:
7
+ value: T
8
+
9
+ def map[U](self, func: Callable[[T], U]) -> Some[U]:
10
+ return Some(func(self.value))
11
+
12
+ def bind[U](self, func: Callable[[T], Maybe[U]]) -> Maybe[U]:
13
+ return func(self.value)
14
+
15
+ def then[U](self, func: Callable[[], Maybe[U]]) -> Maybe[U]:
16
+ return func()
17
+
18
+ def value_or(self, default: T) -> T:
19
+ return self.value
20
+
21
+ def to_optional(self) -> T:
22
+ return self.value
23
+
24
+
25
+ @dataclass(frozen=True, slots=True)
26
+ class Nothing[T]:
27
+ def map[U](self, func: Callable[[T], U]) -> Nothing[U]:
28
+ return Nothing()
29
+
30
+ def bind[U](self, func: Callable[[T], Maybe[U]]) -> Nothing[U]:
31
+ return Nothing()
32
+
33
+ def then[U](self, func: Callable[[], Maybe[U]]) -> Nothing[U]:
34
+ return Nothing()
35
+
36
+ def value_or(self, default: T) -> T:
37
+ return default
38
+
39
+ def to_optional(self) -> None:
40
+ return None
41
+
42
+
43
+ type Maybe[T] = Some[T] | Nothing[T]
44
+
45
+
46
+ def maybe[T](optional: T | None) -> Maybe[T]:
47
+ return Some(optional) if optional is not None else Nothing()
48
+
49
+
50
+ def ensure(cond: bool) -> Maybe[bool]:
51
+ return Some(True) if cond else Nothing()
@@ -1,9 +0,0 @@
1
- Metadata-Version: 2.3
2
- Name: pyfun-zeromode
3
- Version: 0.1.0
4
- Summary: Add your description here
5
- Author: Avilay Parekh
6
- Author-email: Avilay Parekh <avilay@gmail.com>
7
- Requires-Python: >=3.14
8
- Description-Content-Type: text/markdown
9
-
File without changes
@@ -1,4 +0,0 @@
1
- from pyfun.maybe import Maybe, Nothing, Some, bind, fmap, unwrap
2
- from pyfun.pipe import Pipe
3
-
4
- __all__ = ["Maybe", "Nothing", "Some", "fmap", "bind", "Pipe", "unwrap"]
@@ -1,47 +0,0 @@
1
- from __future__ import annotations
2
-
3
- from dataclasses import dataclass
4
- from typing import Callable, assert_never
5
-
6
-
7
- @dataclass(frozen=True, slots=True)
8
- class Some[T]:
9
- value: T
10
-
11
-
12
- @dataclass(frozen=True, slots=True)
13
- class Nothing:
14
- pass
15
-
16
-
17
- type Maybe[T] = Some[T] | Nothing
18
-
19
-
20
- def fmap[T, U](container: Maybe[T], func: Callable[[T], U]) -> Maybe[U]:
21
- match container:
22
- case Some(v):
23
- return Some(func(v))
24
- case Nothing():
25
- return Nothing()
26
- case _ as unreachable:
27
- assert_never(unreachable)
28
-
29
-
30
- def unwrap[T](container: Maybe[T]) -> T:
31
- match container:
32
- case Some(v):
33
- return v
34
- case Nothing():
35
- raise RuntimeError("nothing to unwrap")
36
- case _ as never:
37
- assert_never(never)
38
-
39
-
40
- def bind[T, U](container: Maybe[T], func: Callable[[T], Maybe[U]]) -> Maybe[U]:
41
- match container:
42
- case Some(v):
43
- return func(v)
44
- case Nothing():
45
- return Nothing()
46
- case _ as unreachable:
47
- assert_never(unreachable)