uogtad 0.2.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.
- uogtad-0.2.0/LICENSE +21 -0
- uogtad-0.2.0/PKG-INFO +142 -0
- uogtad-0.2.0/README.md +117 -0
- uogtad-0.2.0/pyproject.toml +56 -0
- uogtad-0.2.0/setup.cfg +4 -0
- uogtad-0.2.0/uogtad/__init__.py +7 -0
- uogtad-0.2.0/uogtad/either.py +139 -0
- uogtad-0.2.0/uogtad/fallible.py +95 -0
- uogtad-0.2.0/uogtad/maybe.py +126 -0
- uogtad-0.2.0/uogtad/py.typed +1 -0
- uogtad-0.2.0/uogtad/test_properties.py +164 -0
- uogtad-0.2.0/uogtad/test_uogtad.py +145 -0
- uogtad-0.2.0/uogtad.egg-info/PKG-INFO +142 -0
- uogtad-0.2.0/uogtad.egg-info/SOURCES.txt +15 -0
- uogtad-0.2.0/uogtad.egg-info/dependency_links.txt +1 -0
- uogtad-0.2.0/uogtad.egg-info/requires.txt +8 -0
- uogtad-0.2.0/uogtad.egg-info/top_level.txt +1 -0
uogtad-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 uogtad contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
uogtad-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: uogtad
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Typed functional control containers for Python
|
|
5
|
+
Author: uogtad contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/blakehawkins/uogtad
|
|
8
|
+
Project-URL: Issues, https://github.com/blakehawkins/uogtad/issues
|
|
9
|
+
Project-URL: Repository, https://github.com/blakehawkins/uogtad.git
|
|
10
|
+
Keywords: either,functional-programming,maybe,result,typing
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.15
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: hypothesis>=6; extra == "test"
|
|
20
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
21
|
+
Provides-Extra: typecheck
|
|
22
|
+
Requires-Dist: mypy>=1.19; extra == "typecheck"
|
|
23
|
+
Requires-Dist: pyright>=1.1.408; extra == "typecheck"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# uoɥʇʎd
|
|
27
|
+
|
|
28
|
+
[](https://github.com/blakehawkins/uogtad/actions/workflows/ci.yml)
|
|
29
|
+
[](https://docs.python.org/3.15/)
|
|
30
|
+
[](https://mypy-lang.org/)
|
|
31
|
+
[](https://github.com/microsoft/pyright)
|
|
32
|
+
[](https://opensource.org/license/mit)
|
|
33
|
+
|
|
34
|
+
A functional control library for python in the same vein as io.vavr.control for java.
|
|
35
|
+
|
|
36
|
+
Provides three immutable, typed control containers:
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
Either.new(value) # Left(value)
|
|
40
|
+
Either.right(error) # Right(error)
|
|
41
|
+
Maybe.new(value) # Some(value), even when value is None
|
|
42
|
+
Maybe.empty() # Empty()
|
|
43
|
+
Maybe.of_optional(value) # Empty() for None, otherwise Some(value)
|
|
44
|
+
Fallible(computation) # captures Exception, but not KeyboardInterrupt/SystemExit
|
|
45
|
+
Fallible(computation, ValueError) # captures only ValueError (and subclasses)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Example usage:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from typing import Literal
|
|
52
|
+
|
|
53
|
+
from uogtad import Either, Fallible
|
|
54
|
+
|
|
55
|
+
def raises() -> str:
|
|
56
|
+
raise RuntimeError("tada")
|
|
57
|
+
|
|
58
|
+
tada = Fallible(raises).as_result().swap().map(lambda exc: str(exc.args[0])).narrow().narrow()
|
|
59
|
+
assert tada == "tada"
|
|
60
|
+
|
|
61
|
+
# Unexpected exceptions remain bugs instead of becoming values. A tuple works
|
|
62
|
+
# just like an ``except`` clause when several exception types are expected.
|
|
63
|
+
parsed = Fallible(lambda: int("not a number"), (ValueError, RuntimeError))
|
|
64
|
+
if failure := parsed.maybe_exception():
|
|
65
|
+
# ``failure.value`` is statically narrowed to ValueError | RuntimeError.
|
|
66
|
+
assert isinstance(failure.value, ValueError)
|
|
67
|
+
|
|
68
|
+
def categorise(num: int) -> Either[Literal['A'], Literal['B']]:
|
|
69
|
+
if num == 0:
|
|
70
|
+
return Either.new('A') # Either is left-biased, like Result[T, E].
|
|
71
|
+
return Either.right('B')
|
|
72
|
+
|
|
73
|
+
results = list(map(categorise, [0, 1, 0, 2, 0, 3]))
|
|
74
|
+
assert [result.is_left() for result in results] == [True, False, True, False, True, False]
|
|
75
|
+
|
|
76
|
+
result = categorise(0)
|
|
77
|
+
if left := result.maybe_left():
|
|
78
|
+
# Static checkers narrow `left` to Left[Literal['A']].
|
|
79
|
+
assert left.value == "A"
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# Ops
|
|
85
|
+
|
|
86
|
+
Install the latest release from PyPI (Python 3.15 or newer):
|
|
87
|
+
|
|
88
|
+
```shell
|
|
89
|
+
python -m pip install uogtad
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Install the current `master` branch directly from GitHub (Python 3.15 or newer)
|
|
93
|
+
with pip:
|
|
94
|
+
|
|
95
|
+
```shell
|
|
96
|
+
python -m pip install "uogtad @ git+https://github.com/blakehawkins/uogtad.git@master"
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Or add the same PyPI-compatible Git dependency to a Pixi project:
|
|
100
|
+
|
|
101
|
+
```shell
|
|
102
|
+
pixi add --pypi "uogtad @ git+https://github.com/blakehawkins/uogtad.git@master"
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Run the test suite:
|
|
106
|
+
|
|
107
|
+
```shell
|
|
108
|
+
pixi run python -m pytest
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Build and validate the PyPI distributions:
|
|
112
|
+
|
|
113
|
+
```shell
|
|
114
|
+
pixi run package
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Releases
|
|
118
|
+
|
|
119
|
+
Releases use [Release Please](https://github.com/googleapis/release-please#readme)
|
|
120
|
+
and [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/), so no
|
|
121
|
+
GitHub repository secrets are required.
|
|
122
|
+
|
|
123
|
+
## Comparison with other libraries
|
|
124
|
+
|
|
125
|
+
[`returns`](https://returns.readthedocs.io/) is a broad collection of typed
|
|
126
|
+
functional abstractions, including IO-aware and asynchronous containers. Its
|
|
127
|
+
decorators, point-free helpers, and `flow` utilities encourage building
|
|
128
|
+
annotated function pipelines. Choose it when an application benefits from that
|
|
129
|
+
larger functional-programming ecosystem and composition style.
|
|
130
|
+
|
|
131
|
+
[`Expression`](https://expression.readthedocs.io/) is inspired by F# and
|
|
132
|
+
provides discriminated unions, computation expressions, immutable collections,
|
|
133
|
+
and functional utilities in addition to `Option` and `Result`. Its decorators,
|
|
134
|
+
free functions, and `pipe` helpers support an F#-style pipeline-oriented
|
|
135
|
+
application design. Choose it when those abstractions should shape more of the
|
|
136
|
+
application.
|
|
137
|
+
|
|
138
|
+
`uogtad` deliberately has a smaller scope: `Either`, `Maybe`, and `Fallible`,
|
|
139
|
+
with operations exposed directly as methods. It intentionally avoids
|
|
140
|
+
decorator-driven control flow, free-function combinators, and a pipeline DSL.
|
|
141
|
+
Choose it when ordinary method chaining, Python pattern matching, and a compact
|
|
142
|
+
API are preferable.
|
uogtad-0.2.0/README.md
ADDED
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
# uoɥʇʎd
|
|
2
|
+
|
|
3
|
+
[](https://github.com/blakehawkins/uogtad/actions/workflows/ci.yml)
|
|
4
|
+
[](https://docs.python.org/3.15/)
|
|
5
|
+
[](https://mypy-lang.org/)
|
|
6
|
+
[](https://github.com/microsoft/pyright)
|
|
7
|
+
[](https://opensource.org/license/mit)
|
|
8
|
+
|
|
9
|
+
A functional control library for python in the same vein as io.vavr.control for java.
|
|
10
|
+
|
|
11
|
+
Provides three immutable, typed control containers:
|
|
12
|
+
|
|
13
|
+
```python
|
|
14
|
+
Either.new(value) # Left(value)
|
|
15
|
+
Either.right(error) # Right(error)
|
|
16
|
+
Maybe.new(value) # Some(value), even when value is None
|
|
17
|
+
Maybe.empty() # Empty()
|
|
18
|
+
Maybe.of_optional(value) # Empty() for None, otherwise Some(value)
|
|
19
|
+
Fallible(computation) # captures Exception, but not KeyboardInterrupt/SystemExit
|
|
20
|
+
Fallible(computation, ValueError) # captures only ValueError (and subclasses)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
Example usage:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
from typing import Literal
|
|
27
|
+
|
|
28
|
+
from uogtad import Either, Fallible
|
|
29
|
+
|
|
30
|
+
def raises() -> str:
|
|
31
|
+
raise RuntimeError("tada")
|
|
32
|
+
|
|
33
|
+
tada = Fallible(raises).as_result().swap().map(lambda exc: str(exc.args[0])).narrow().narrow()
|
|
34
|
+
assert tada == "tada"
|
|
35
|
+
|
|
36
|
+
# Unexpected exceptions remain bugs instead of becoming values. A tuple works
|
|
37
|
+
# just like an ``except`` clause when several exception types are expected.
|
|
38
|
+
parsed = Fallible(lambda: int("not a number"), (ValueError, RuntimeError))
|
|
39
|
+
if failure := parsed.maybe_exception():
|
|
40
|
+
# ``failure.value`` is statically narrowed to ValueError | RuntimeError.
|
|
41
|
+
assert isinstance(failure.value, ValueError)
|
|
42
|
+
|
|
43
|
+
def categorise(num: int) -> Either[Literal['A'], Literal['B']]:
|
|
44
|
+
if num == 0:
|
|
45
|
+
return Either.new('A') # Either is left-biased, like Result[T, E].
|
|
46
|
+
return Either.right('B')
|
|
47
|
+
|
|
48
|
+
results = list(map(categorise, [0, 1, 0, 2, 0, 3]))
|
|
49
|
+
assert [result.is_left() for result in results] == [True, False, True, False, True, False]
|
|
50
|
+
|
|
51
|
+
result = categorise(0)
|
|
52
|
+
if left := result.maybe_left():
|
|
53
|
+
# Static checkers narrow `left` to Left[Literal['A']].
|
|
54
|
+
assert left.value == "A"
|
|
55
|
+
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
# Ops
|
|
60
|
+
|
|
61
|
+
Install the latest release from PyPI (Python 3.15 or newer):
|
|
62
|
+
|
|
63
|
+
```shell
|
|
64
|
+
python -m pip install uogtad
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
Install the current `master` branch directly from GitHub (Python 3.15 or newer)
|
|
68
|
+
with pip:
|
|
69
|
+
|
|
70
|
+
```shell
|
|
71
|
+
python -m pip install "uogtad @ git+https://github.com/blakehawkins/uogtad.git@master"
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Or add the same PyPI-compatible Git dependency to a Pixi project:
|
|
75
|
+
|
|
76
|
+
```shell
|
|
77
|
+
pixi add --pypi "uogtad @ git+https://github.com/blakehawkins/uogtad.git@master"
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
Run the test suite:
|
|
81
|
+
|
|
82
|
+
```shell
|
|
83
|
+
pixi run python -m pytest
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Build and validate the PyPI distributions:
|
|
87
|
+
|
|
88
|
+
```shell
|
|
89
|
+
pixi run package
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
### Releases
|
|
93
|
+
|
|
94
|
+
Releases use [Release Please](https://github.com/googleapis/release-please#readme)
|
|
95
|
+
and [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/), so no
|
|
96
|
+
GitHub repository secrets are required.
|
|
97
|
+
|
|
98
|
+
## Comparison with other libraries
|
|
99
|
+
|
|
100
|
+
[`returns`](https://returns.readthedocs.io/) is a broad collection of typed
|
|
101
|
+
functional abstractions, including IO-aware and asynchronous containers. Its
|
|
102
|
+
decorators, point-free helpers, and `flow` utilities encourage building
|
|
103
|
+
annotated function pipelines. Choose it when an application benefits from that
|
|
104
|
+
larger functional-programming ecosystem and composition style.
|
|
105
|
+
|
|
106
|
+
[`Expression`](https://expression.readthedocs.io/) is inspired by F# and
|
|
107
|
+
provides discriminated unions, computation expressions, immutable collections,
|
|
108
|
+
and functional utilities in addition to `Option` and `Result`. Its decorators,
|
|
109
|
+
free functions, and `pipe` helpers support an F#-style pipeline-oriented
|
|
110
|
+
application design. Choose it when those abstractions should shape more of the
|
|
111
|
+
application.
|
|
112
|
+
|
|
113
|
+
`uogtad` deliberately has a smaller scope: `Either`, `Maybe`, and `Fallible`,
|
|
114
|
+
with operations exposed directly as methods. It intentionally avoids
|
|
115
|
+
decorator-driven control flow, free-function combinators, and a pipeline DSL.
|
|
116
|
+
Choose it when ordinary method chaining, Python pattern matching, and a compact
|
|
117
|
+
API are preferable.
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "uogtad"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Typed functional control containers for Python"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.15"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{name = "uogtad contributors"}]
|
|
13
|
+
classifiers = [
|
|
14
|
+
"Development Status :: 3 - Alpha",
|
|
15
|
+
"Programming Language :: Python :: 3",
|
|
16
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
17
|
+
"Typing :: Typed",
|
|
18
|
+
]
|
|
19
|
+
keywords = ["either", "functional-programming", "maybe", "result", "typing"]
|
|
20
|
+
|
|
21
|
+
[project.urls]
|
|
22
|
+
Homepage = "https://github.com/blakehawkins/uogtad"
|
|
23
|
+
Issues = "https://github.com/blakehawkins/uogtad/issues"
|
|
24
|
+
Repository = "https://github.com/blakehawkins/uogtad.git"
|
|
25
|
+
|
|
26
|
+
[project.optional-dependencies]
|
|
27
|
+
test = ["hypothesis>=6", "pytest>=7"]
|
|
28
|
+
typecheck = ["mypy>=1.19", "pyright>=1.1.408"]
|
|
29
|
+
|
|
30
|
+
[tool.setuptools.package-data]
|
|
31
|
+
uogtad = ["py.typed"]
|
|
32
|
+
|
|
33
|
+
[tool.pytest.ini_options]
|
|
34
|
+
testpaths = ["uogtad"]
|
|
35
|
+
|
|
36
|
+
[tool.mypy]
|
|
37
|
+
strict = true
|
|
38
|
+
files = ["uogtad"]
|
|
39
|
+
|
|
40
|
+
[tool.pyright]
|
|
41
|
+
pythonVersion = "3.15"
|
|
42
|
+
|
|
43
|
+
[tool.pixi.workspace]
|
|
44
|
+
channels = ["conda-forge/label/python_rc", "conda-forge"]
|
|
45
|
+
platforms = ["linux-64"]
|
|
46
|
+
|
|
47
|
+
[tool.pixi.dependencies]
|
|
48
|
+
python = "3.15.*"
|
|
49
|
+
pip = ">=25"
|
|
50
|
+
|
|
51
|
+
[tool.pixi.pypi-dependencies]
|
|
52
|
+
build = ">=1"
|
|
53
|
+
twine = ">=6"
|
|
54
|
+
|
|
55
|
+
[tool.pixi.tasks]
|
|
56
|
+
package = "rm -rf build dist *.egg-info && python -m build && python -m twine check --strict dist/*"
|
uogtad-0.2.0/setup.cfg
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
"""Small, typed containers for functional-style control flow."""
|
|
2
|
+
|
|
3
|
+
from uogtad.either import Either, Left, Right
|
|
4
|
+
from uogtad.fallible import Fallible
|
|
5
|
+
from uogtad.maybe import Empty, Maybe, Some
|
|
6
|
+
|
|
7
|
+
__all__ = ["Either", "Left", "Right", "Maybe", "Some", "Empty", "Fallible"]
|
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""The two-case :class:`Either` container."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Callable, Never
|
|
5
|
+
|
|
6
|
+
lazy import uogtad.maybe as maybe_module
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Either[T, U]:
|
|
10
|
+
"""A value in exactly one of two cases: :class:`Left` or :class:`Right`."""
|
|
11
|
+
|
|
12
|
+
@classmethod
|
|
13
|
+
def new(cls, value: T) -> Either[T, U]:
|
|
14
|
+
"""Create a left value (``Either`` is left-biased)."""
|
|
15
|
+
return Left[T, U](value)
|
|
16
|
+
|
|
17
|
+
@classmethod
|
|
18
|
+
def right(cls, value: U) -> Either[T, U]:
|
|
19
|
+
"""Create a right value."""
|
|
20
|
+
return Right[U, T](value)
|
|
21
|
+
|
|
22
|
+
def is_left(self) -> bool:
|
|
23
|
+
match self:
|
|
24
|
+
case Left():
|
|
25
|
+
return True
|
|
26
|
+
case Right():
|
|
27
|
+
return False
|
|
28
|
+
case _:
|
|
29
|
+
raise TypeError("unknown Either variant")
|
|
30
|
+
|
|
31
|
+
def is_right(self) -> bool:
|
|
32
|
+
return not self.is_left()
|
|
33
|
+
|
|
34
|
+
def maybe_left(self) -> Left[T, U] | None:
|
|
35
|
+
"""Return the concrete left variant, or ``None`` when this is right."""
|
|
36
|
+
match self:
|
|
37
|
+
case Left() as left:
|
|
38
|
+
return left
|
|
39
|
+
case Right():
|
|
40
|
+
return None
|
|
41
|
+
case _:
|
|
42
|
+
raise TypeError("unknown Either variant")
|
|
43
|
+
|
|
44
|
+
def maybe_right(self) -> Right[U, T] | None:
|
|
45
|
+
"""Return the concrete right variant, or ``None`` when this is left."""
|
|
46
|
+
match self:
|
|
47
|
+
case Left():
|
|
48
|
+
return None
|
|
49
|
+
case Right() as right:
|
|
50
|
+
return right
|
|
51
|
+
case _:
|
|
52
|
+
raise TypeError("unknown Either variant")
|
|
53
|
+
|
|
54
|
+
def context(self, context: str) -> Either[T, RuntimeError]:
|
|
55
|
+
match self:
|
|
56
|
+
case Left(value):
|
|
57
|
+
return Left(value)
|
|
58
|
+
case Right(value):
|
|
59
|
+
return Right(RuntimeError(context, value))
|
|
60
|
+
case _:
|
|
61
|
+
raise TypeError("unknown Either variant")
|
|
62
|
+
|
|
63
|
+
def swap(self) -> Either[U, T]:
|
|
64
|
+
match self:
|
|
65
|
+
case Left(value):
|
|
66
|
+
return Right(value)
|
|
67
|
+
case Right(value):
|
|
68
|
+
return Left(value)
|
|
69
|
+
case _:
|
|
70
|
+
raise TypeError("unknown Either variant")
|
|
71
|
+
|
|
72
|
+
def or_else[V](self, otherwise: Callable[[U], V]) -> T | V:
|
|
73
|
+
if (left := self.maybe_left()) is not None:
|
|
74
|
+
return left.value
|
|
75
|
+
if (right := self.maybe_right()) is not None:
|
|
76
|
+
return otherwise(right.value)
|
|
77
|
+
raise TypeError("unknown Either variant")
|
|
78
|
+
|
|
79
|
+
def map[V](self, function: Callable[[T], V]) -> Either[V, U]:
|
|
80
|
+
match self:
|
|
81
|
+
case Left(value):
|
|
82
|
+
return Left(function(value))
|
|
83
|
+
case Right(value):
|
|
84
|
+
return Right(value)
|
|
85
|
+
case _:
|
|
86
|
+
raise TypeError("unknown Either variant")
|
|
87
|
+
|
|
88
|
+
def flat_map[V](self, function: Callable[[T], Either[V, U]]) -> Either[V, U]:
|
|
89
|
+
match self:
|
|
90
|
+
case Left(value):
|
|
91
|
+
return function(value)
|
|
92
|
+
case Right(value):
|
|
93
|
+
return Right(value)
|
|
94
|
+
case _:
|
|
95
|
+
raise TypeError("unknown Either variant")
|
|
96
|
+
|
|
97
|
+
def map_right[V](self, function: Callable[[U], V]) -> Either[T, V]:
|
|
98
|
+
match self:
|
|
99
|
+
case Left(value):
|
|
100
|
+
return Left(value)
|
|
101
|
+
case Right(value):
|
|
102
|
+
return Right(function(value))
|
|
103
|
+
case _:
|
|
104
|
+
raise TypeError("unknown Either variant")
|
|
105
|
+
|
|
106
|
+
def flat_map_right[V](self, function: Callable[[U], Either[T, V]]) -> Either[T, V]:
|
|
107
|
+
match self:
|
|
108
|
+
case Left(value):
|
|
109
|
+
return Left(value)
|
|
110
|
+
case Right(value):
|
|
111
|
+
return function(value)
|
|
112
|
+
case _:
|
|
113
|
+
raise TypeError("unknown Either variant")
|
|
114
|
+
|
|
115
|
+
def narrow(self) -> maybe_module.Maybe[T]:
|
|
116
|
+
match self:
|
|
117
|
+
case Left(value):
|
|
118
|
+
return maybe_module.Some(value)
|
|
119
|
+
case Right():
|
|
120
|
+
return maybe_module.Empty[T]()
|
|
121
|
+
case _:
|
|
122
|
+
raise TypeError("unknown Either variant")
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass(frozen=True)
|
|
126
|
+
class Left[L, R = Never](Either[L, R]):
|
|
127
|
+
"""The left case of :class:`Either`."""
|
|
128
|
+
|
|
129
|
+
value: L
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
@dataclass(frozen=True)
|
|
133
|
+
class Right[R, L = Never](Either[L, R]):
|
|
134
|
+
"""The right case of :class:`Either`."""
|
|
135
|
+
|
|
136
|
+
value: R
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
__all__ = ["Either", "Left", "Right"]
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""The exception-capturing :class:`Fallible` container."""
|
|
2
|
+
|
|
3
|
+
from typing import Callable, cast, overload
|
|
4
|
+
|
|
5
|
+
from uogtad.either import Either, Left, Right
|
|
6
|
+
from uogtad.maybe import Maybe
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Fallible[F, E: Exception = Exception]:
|
|
10
|
+
"""The return value or a selected exception from a computation.
|
|
11
|
+
|
|
12
|
+
By default, all ordinary exceptions are captured. Pass an exception class
|
|
13
|
+
or tuple of exception classes to let unrelated exceptions propagate.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
@overload
|
|
17
|
+
def __init__(self, computation: Callable[[], F]) -> None: ...
|
|
18
|
+
|
|
19
|
+
@overload
|
|
20
|
+
def __init__(
|
|
21
|
+
self,
|
|
22
|
+
computation: Callable[[], F],
|
|
23
|
+
exceptions: type[E] | tuple[type[E], ...],
|
|
24
|
+
) -> None: ...
|
|
25
|
+
|
|
26
|
+
def __init__(
|
|
27
|
+
self,
|
|
28
|
+
computation: Callable[[], F],
|
|
29
|
+
exceptions: type[E] | tuple[type[E], ...] = cast(type[E], Exception),
|
|
30
|
+
) -> None:
|
|
31
|
+
self._exceptions = exceptions
|
|
32
|
+
try:
|
|
33
|
+
self._result: Either[F, E] = Either[F, E].new(computation())
|
|
34
|
+
except exceptions as error:
|
|
35
|
+
self._result = Either[F, E].right(error)
|
|
36
|
+
|
|
37
|
+
@classmethod
|
|
38
|
+
def _from_result(
|
|
39
|
+
cls,
|
|
40
|
+
result: Either[F, E],
|
|
41
|
+
exceptions: type[E] | tuple[type[E], ...],
|
|
42
|
+
) -> Fallible[F, E]:
|
|
43
|
+
instance = cls.__new__(cls)
|
|
44
|
+
instance._result = result
|
|
45
|
+
instance._exceptions = exceptions
|
|
46
|
+
return instance
|
|
47
|
+
|
|
48
|
+
def as_result(self) -> Either[F, E]:
|
|
49
|
+
return self._result
|
|
50
|
+
|
|
51
|
+
def is_success(self) -> bool:
|
|
52
|
+
return self._result.is_left()
|
|
53
|
+
|
|
54
|
+
def is_exception(self) -> bool:
|
|
55
|
+
return self._result.is_right()
|
|
56
|
+
|
|
57
|
+
def maybe_success(self) -> Left[F, E] | None:
|
|
58
|
+
"""Return the concrete successful result, or ``None`` on failure."""
|
|
59
|
+
return self._result.maybe_left()
|
|
60
|
+
|
|
61
|
+
def maybe_exception(self) -> Right[E, F] | None:
|
|
62
|
+
"""Return the concrete failed result, or ``None`` on success."""
|
|
63
|
+
return self._result.maybe_right()
|
|
64
|
+
|
|
65
|
+
def map[V](self, function: Callable[[F], V]) -> Fallible[V, E]:
|
|
66
|
+
match self._result:
|
|
67
|
+
case Left(value):
|
|
68
|
+
return Fallible[V, E](lambda: function(value), self._exceptions)
|
|
69
|
+
case Right(error):
|
|
70
|
+
return Fallible[V, E]._from_result(Right(error), self._exceptions)
|
|
71
|
+
case _:
|
|
72
|
+
raise TypeError("unknown Either variant")
|
|
73
|
+
|
|
74
|
+
def flat_map[V](
|
|
75
|
+
self, function: Callable[[F], Fallible[V, E]]
|
|
76
|
+
) -> Fallible[V, E]:
|
|
77
|
+
match self._result:
|
|
78
|
+
case Left(value):
|
|
79
|
+
try:
|
|
80
|
+
return function(value)
|
|
81
|
+
except self._exceptions as error:
|
|
82
|
+
return Fallible[V, E]._from_result(Right(error), self._exceptions)
|
|
83
|
+
case Right(error):
|
|
84
|
+
return Fallible[V, E]._from_result(Right(error), self._exceptions)
|
|
85
|
+
case _:
|
|
86
|
+
raise TypeError("unknown Either variant")
|
|
87
|
+
|
|
88
|
+
def narrow(self) -> Maybe[F]:
|
|
89
|
+
return self._result.narrow()
|
|
90
|
+
|
|
91
|
+
def or_else[V](self, recovery: Callable[[E], V]) -> F | V:
|
|
92
|
+
return self._result.or_else(recovery)
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
__all__ = ["Fallible"]
|
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""The optional-value :class:`Maybe` container."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from typing import Callable, Never
|
|
5
|
+
|
|
6
|
+
from uogtad.either import Either, Left, Right
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class Maybe[T]:
|
|
10
|
+
"""A value represented by either :class:`Some` or :class:`Empty`.
|
|
11
|
+
|
|
12
|
+
``Maybe(value)`` creates ``Some(value)``. Unlike the previous implementation,
|
|
13
|
+
``None`` is a valid present value.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
def __new__(cls, value: T) -> Maybe[T]:
|
|
17
|
+
return Some(value)
|
|
18
|
+
|
|
19
|
+
@classmethod
|
|
20
|
+
def new(cls, value: T) -> Maybe[T]:
|
|
21
|
+
"""Create a present value, including when ``value`` is falsy."""
|
|
22
|
+
return Some(value)
|
|
23
|
+
|
|
24
|
+
@classmethod
|
|
25
|
+
def empty(cls) -> Maybe[T]:
|
|
26
|
+
return Empty[T]()
|
|
27
|
+
|
|
28
|
+
@classmethod
|
|
29
|
+
def of_optional(cls, value: T | None) -> Maybe[T]:
|
|
30
|
+
"""Create ``Empty`` from ``None`` and ``Some`` from any other value."""
|
|
31
|
+
match value:
|
|
32
|
+
case None:
|
|
33
|
+
return Empty[T]()
|
|
34
|
+
case _:
|
|
35
|
+
return Some(value)
|
|
36
|
+
|
|
37
|
+
def is_present(self) -> bool:
|
|
38
|
+
match self:
|
|
39
|
+
case Some():
|
|
40
|
+
return True
|
|
41
|
+
case Empty():
|
|
42
|
+
return False
|
|
43
|
+
case _:
|
|
44
|
+
raise TypeError("unknown Maybe variant")
|
|
45
|
+
|
|
46
|
+
def maybe_some(self) -> Some[T] | None:
|
|
47
|
+
"""Return the concrete present variant, or ``None`` when empty."""
|
|
48
|
+
match self:
|
|
49
|
+
case Some() as some:
|
|
50
|
+
return some
|
|
51
|
+
case Empty():
|
|
52
|
+
return None
|
|
53
|
+
case _:
|
|
54
|
+
raise TypeError("unknown Maybe variant")
|
|
55
|
+
|
|
56
|
+
def context(self, context: str) -> Either[T, RuntimeError]:
|
|
57
|
+
match self:
|
|
58
|
+
case Some(value):
|
|
59
|
+
return Either[T, RuntimeError].new(value)
|
|
60
|
+
case Empty():
|
|
61
|
+
return Either[T, RuntimeError].right(RuntimeError(context))
|
|
62
|
+
case _:
|
|
63
|
+
raise TypeError("unknown Maybe variant")
|
|
64
|
+
|
|
65
|
+
def or_else[V](self, instead: V) -> T | V:
|
|
66
|
+
if (some := self.maybe_some()) is not None:
|
|
67
|
+
return some.value
|
|
68
|
+
return instead
|
|
69
|
+
|
|
70
|
+
def or_else_get[V](self, instead_provider: Callable[[], V]) -> T | V:
|
|
71
|
+
if (some := self.maybe_some()) is not None:
|
|
72
|
+
return some.value
|
|
73
|
+
return instead_provider()
|
|
74
|
+
|
|
75
|
+
def filter(self, clause: Callable[[T], bool]) -> Maybe[T]:
|
|
76
|
+
match self:
|
|
77
|
+
case Some(value) if clause(value):
|
|
78
|
+
return Some(value)
|
|
79
|
+
case Some() | Empty():
|
|
80
|
+
return Empty[T]()
|
|
81
|
+
case _:
|
|
82
|
+
raise TypeError("unknown Maybe variant")
|
|
83
|
+
|
|
84
|
+
def map[V](self, function: Callable[[T], V]) -> Maybe[V]:
|
|
85
|
+
match self:
|
|
86
|
+
case Some(value):
|
|
87
|
+
return Some(function(value))
|
|
88
|
+
case Empty():
|
|
89
|
+
return Empty[V]()
|
|
90
|
+
case _:
|
|
91
|
+
raise TypeError("unknown Maybe variant")
|
|
92
|
+
|
|
93
|
+
def narrow(self) -> T | None:
|
|
94
|
+
if (some := self.maybe_some()) is not None:
|
|
95
|
+
return some.value
|
|
96
|
+
return None
|
|
97
|
+
|
|
98
|
+
def flat_map[V](self, function: Callable[[T], Maybe[V]]) -> Maybe[V]:
|
|
99
|
+
match self:
|
|
100
|
+
case Some(value):
|
|
101
|
+
return function(value)
|
|
102
|
+
case Empty():
|
|
103
|
+
return Empty[V]()
|
|
104
|
+
case _:
|
|
105
|
+
raise TypeError("unknown Maybe variant")
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
@dataclass(frozen=True)
|
|
109
|
+
class Some[L](Maybe[L]):
|
|
110
|
+
"""The present case of :class:`Maybe`."""
|
|
111
|
+
|
|
112
|
+
value: L
|
|
113
|
+
|
|
114
|
+
def __new__(cls, value: L) -> Some[L]:
|
|
115
|
+
return object.__new__(cls)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class Empty[T = Never](Maybe[T]):
|
|
120
|
+
"""The absent case of :class:`Maybe`."""
|
|
121
|
+
|
|
122
|
+
def __new__(cls) -> Empty[T]:
|
|
123
|
+
return object.__new__(cls)
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
__all__ = ["Maybe", "Some", "Empty"]
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
"""Property-based tests for the public container laws and invariants."""
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
4
|
+
|
|
5
|
+
from hypothesis import given
|
|
6
|
+
from hypothesis import strategies as st
|
|
7
|
+
|
|
8
|
+
from uogtad import Either, Empty, Fallible, Left, Maybe, Right, Some
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
values = st.one_of(
|
|
12
|
+
st.none(),
|
|
13
|
+
st.booleans(),
|
|
14
|
+
st.integers(),
|
|
15
|
+
st.text(),
|
|
16
|
+
st.lists(st.integers()),
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
@given(values)
|
|
21
|
+
def test_either_left_has_exactly_one_variant(value: object) -> None:
|
|
22
|
+
result: Either[object, object] = Either.new(value)
|
|
23
|
+
|
|
24
|
+
assert result.is_left()
|
|
25
|
+
assert not result.is_right()
|
|
26
|
+
assert result.maybe_left() == Left(value)
|
|
27
|
+
assert result.maybe_right() is None
|
|
28
|
+
assert result.narrow() == Some(value)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@given(values)
|
|
32
|
+
def test_either_right_has_exactly_one_variant(value: object) -> None:
|
|
33
|
+
result: Either[object, object] = Either.right(value)
|
|
34
|
+
|
|
35
|
+
assert not result.is_left()
|
|
36
|
+
assert result.is_right()
|
|
37
|
+
assert result.maybe_left() is None
|
|
38
|
+
assert result.maybe_right() == Right(value)
|
|
39
|
+
assert result.narrow() == Empty()
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
@given(values, st.booleans())
|
|
43
|
+
def test_either_swap_is_an_involution(value: object, is_left: bool) -> None:
|
|
44
|
+
result: Either[object, object]
|
|
45
|
+
if is_left:
|
|
46
|
+
result = Either.new(value)
|
|
47
|
+
else:
|
|
48
|
+
result = Either.right(value)
|
|
49
|
+
|
|
50
|
+
assert result.swap().swap() == result
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
@given(st.integers(), st.integers(), st.integers())
|
|
54
|
+
def test_either_map_obeys_identity_and_composition(value: int, addend: int, factor: int) -> None:
|
|
55
|
+
result: Either[int, str] = Either.new(value)
|
|
56
|
+
|
|
57
|
+
def add(item: int) -> int:
|
|
58
|
+
return item + addend
|
|
59
|
+
|
|
60
|
+
def multiply(item: int) -> int:
|
|
61
|
+
return item * factor
|
|
62
|
+
|
|
63
|
+
assert result.map(lambda item: item) == result
|
|
64
|
+
assert result.map(add).map(multiply) == result.map(lambda item: multiply(add(item)))
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
@given(st.text(), st.text())
|
|
68
|
+
def test_either_right_short_circuits_left_operations(value: str, fallback: str) -> None:
|
|
69
|
+
result: Either[int, str] = Either.right(value)
|
|
70
|
+
called = False
|
|
71
|
+
|
|
72
|
+
def left_callback(_: int) -> int:
|
|
73
|
+
nonlocal called
|
|
74
|
+
called = True
|
|
75
|
+
return 0
|
|
76
|
+
|
|
77
|
+
assert result.map(left_callback) == Right(value)
|
|
78
|
+
assert result.flat_map(lambda item: Either.new(left_callback(item))) == Right(value)
|
|
79
|
+
assert result.or_else(lambda _: fallback) == fallback
|
|
80
|
+
assert not called
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
@given(values)
|
|
84
|
+
def test_maybe_new_always_creates_some(value: object) -> None:
|
|
85
|
+
result = Maybe.new(value)
|
|
86
|
+
|
|
87
|
+
assert result == Some(value)
|
|
88
|
+
assert result.is_present()
|
|
89
|
+
assert result.maybe_some() == Some(value)
|
|
90
|
+
assert result.narrow() == value
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@given(values)
|
|
94
|
+
def test_maybe_of_optional_matches_none_semantics(value: object) -> None:
|
|
95
|
+
result = Maybe.of_optional(value)
|
|
96
|
+
|
|
97
|
+
if value is None:
|
|
98
|
+
assert result == Empty()
|
|
99
|
+
else:
|
|
100
|
+
assert result == Some(value)
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@given(st.integers(), st.integers(), st.integers())
|
|
104
|
+
def test_maybe_map_obeys_identity_and_composition(value: int, addend: int, factor: int) -> None:
|
|
105
|
+
result = Maybe.new(value)
|
|
106
|
+
|
|
107
|
+
def add(item: int) -> int:
|
|
108
|
+
return item + addend
|
|
109
|
+
|
|
110
|
+
def multiply(item: int) -> int:
|
|
111
|
+
return item * factor
|
|
112
|
+
|
|
113
|
+
assert result.map(lambda item: item) == result
|
|
114
|
+
assert result.map(add).map(multiply) == result.map(lambda item: multiply(add(item)))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@given(st.integers(), st.integers())
|
|
118
|
+
def test_maybe_filter_matches_predicate(value: int, divisor: int) -> None:
|
|
119
|
+
predicate: Callable[[int], bool] = lambda item: item >= divisor
|
|
120
|
+
expected: Maybe[int] = Some(value) if predicate(value) else Empty()
|
|
121
|
+
|
|
122
|
+
assert Maybe.new(value).filter(predicate) == expected
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@given(values, values)
|
|
126
|
+
def test_maybe_fallbacks_are_lazy_for_present_values(value: object, fallback: object) -> None:
|
|
127
|
+
called = False
|
|
128
|
+
|
|
129
|
+
def fallback_provider() -> object:
|
|
130
|
+
nonlocal called
|
|
131
|
+
called = True
|
|
132
|
+
return fallback
|
|
133
|
+
|
|
134
|
+
assert Maybe.new(value).or_else(fallback) == value
|
|
135
|
+
assert Maybe.new(value).or_else_get(fallback_provider) == value
|
|
136
|
+
assert not called
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
@given(st.integers())
|
|
140
|
+
def test_fallible_success_round_trips_and_maps(value: int) -> None:
|
|
141
|
+
result = Fallible(lambda: value)
|
|
142
|
+
|
|
143
|
+
assert result.is_success()
|
|
144
|
+
assert not result.is_exception()
|
|
145
|
+
assert result.as_result() == Left(value)
|
|
146
|
+
assert result.narrow() == Some(value)
|
|
147
|
+
assert result.map(lambda item: item + 1).as_result() == Left(value + 1)
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
@given(st.text(), st.text())
|
|
151
|
+
def test_fallible_failure_preserves_exception_and_recovers(message: str, recovery: str) -> None:
|
|
152
|
+
error = ValueError(message)
|
|
153
|
+
|
|
154
|
+
def fail() -> int:
|
|
155
|
+
raise error
|
|
156
|
+
|
|
157
|
+
result = Fallible(fail)
|
|
158
|
+
|
|
159
|
+
assert not result.is_success()
|
|
160
|
+
assert result.is_exception()
|
|
161
|
+
assert result.maybe_success() is None
|
|
162
|
+
assert result.maybe_exception() == Right(error)
|
|
163
|
+
assert result.map(lambda item: item + 1).as_result() == Right(error)
|
|
164
|
+
assert result.or_else(lambda caught: (caught, recovery)) == (error, recovery)
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
from typing import Literal, Never, assert_type
|
|
2
|
+
|
|
3
|
+
import pytest
|
|
4
|
+
|
|
5
|
+
from uogtad import Either, Empty, Fallible, Left, Maybe, Right, Some
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
@pytest.mark.parametrize("value", [0, "", [], False, None])
|
|
9
|
+
def test_either_preserves_falsy_left_values(value: object) -> None:
|
|
10
|
+
result: Either[object, Never] = Either.new(value)
|
|
11
|
+
assert result.map(lambda item: (item, "mapped")) == Left((value, "mapped"))
|
|
12
|
+
assert result.narrow() == Some(value)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def test_either_cases_support_equality_repr_and_matching() -> None:
|
|
16
|
+
assert Either.new(1) == Either.new(1)
|
|
17
|
+
assert repr(Either.right("error")) == "Right(value='error')"
|
|
18
|
+
match Either.new(None):
|
|
19
|
+
case Left(value):
|
|
20
|
+
assert value is None
|
|
21
|
+
case Right(): # pragma: no cover - protects exhaustiveness at runtime
|
|
22
|
+
pytest.fail("unexpected right")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def test_either_operations() -> None:
|
|
26
|
+
result: Either[int, str] = Either.new(1)
|
|
27
|
+
assert result.map(lambda value: value + 1) == Left(2)
|
|
28
|
+
assert result.flat_map(lambda value: Either.new(value + 2)) == Left(3)
|
|
29
|
+
assert Either.right("bad").map_right(str.upper) == Right("BAD")
|
|
30
|
+
assert Either.right("bad").swap() == Left("bad")
|
|
31
|
+
assert Either.right("bad").context("failed").is_right()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def test_either_variant_guards_narrow_to_concrete_cases() -> None:
|
|
35
|
+
result: Either[int, str] = Either.new(1)
|
|
36
|
+
if left := result.maybe_left():
|
|
37
|
+
assert left.value + 1 == 2
|
|
38
|
+
else: # pragma: no cover - protects type narrowing at runtime
|
|
39
|
+
pytest.fail("expected left")
|
|
40
|
+
|
|
41
|
+
assert result.maybe_right() is None
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@pytest.mark.parametrize("value", [0, "", [], False, None])
|
|
45
|
+
def test_maybe_preserves_present_falsy_values(value: object) -> None:
|
|
46
|
+
maybe = Maybe(value)
|
|
47
|
+
assert maybe.is_present()
|
|
48
|
+
assert maybe.or_else("fallback") == value
|
|
49
|
+
assert maybe.or_else_get(lambda: "fallback") == value
|
|
50
|
+
assert maybe.filter(lambda _: True) == Some(value)
|
|
51
|
+
assert maybe.map(lambda item: (item, "mapped")) == Some((value, "mapped"))
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def test_empty_maybe() -> None:
|
|
55
|
+
empty: Maybe[int] = Maybe.empty()
|
|
56
|
+
assert empty == Empty()
|
|
57
|
+
assert empty.or_else(99) == 99
|
|
58
|
+
assert empty.flat_map(lambda value: Some(value + 1)) == Empty()
|
|
59
|
+
assert empty.maybe_some() is None
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
@pytest.mark.parametrize("value", [0, "", [], False])
|
|
63
|
+
def test_maybe_of_optional_preserves_non_none_values(value: object) -> None:
|
|
64
|
+
assert Maybe.of_optional(value) == Some(value)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def test_maybe_of_optional_converts_none_to_empty() -> None:
|
|
68
|
+
assert Maybe.of_optional(None) == Empty()
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def test_maybe_guard_narrows_to_some() -> None:
|
|
72
|
+
if some := Maybe(0).maybe_some():
|
|
73
|
+
assert some.value == 0
|
|
74
|
+
else: # pragma: no cover - protects type narrowing at runtime
|
|
75
|
+
pytest.fail("expected some")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
@pytest.mark.parametrize("value", [0, "", [], False, None])
|
|
79
|
+
def test_fallible_preserves_falsy_successes(value: object) -> None:
|
|
80
|
+
result = Fallible(lambda: value)
|
|
81
|
+
assert result.is_success()
|
|
82
|
+
assert result.as_result() == Left(value)
|
|
83
|
+
assert result.or_else(lambda _: "fallback") == value
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def test_fallible_defaults_to_capturing_exception() -> None:
|
|
87
|
+
result = Fallible(lambda: 1)
|
|
88
|
+
assert_type(result, Fallible[int, Exception])
|
|
89
|
+
assert_type(result.maybe_exception(), Right[Exception, int] | None)
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
def test_fallible_map_and_flat_map_capture_callback_errors() -> None:
|
|
93
|
+
mapped = Fallible(lambda: 1).map(lambda _: 1 / 0)
|
|
94
|
+
assert mapped.is_exception()
|
|
95
|
+
mapped_result = mapped.as_result()
|
|
96
|
+
assert isinstance(mapped_result, Right)
|
|
97
|
+
assert isinstance(mapped_result.value, ZeroDivisionError)
|
|
98
|
+
|
|
99
|
+
def fail(_: int) -> Fallible[str]:
|
|
100
|
+
raise ValueError("bad callback")
|
|
101
|
+
|
|
102
|
+
flat_mapped_result = Fallible(lambda: 1).flat_map(fail).as_result()
|
|
103
|
+
assert isinstance(flat_mapped_result, Right)
|
|
104
|
+
assert isinstance(flat_mapped_result.value, ValueError)
|
|
105
|
+
|
|
106
|
+
assert mapped.maybe_success() is None
|
|
107
|
+
assert isinstance(mapped.maybe_exception(), Right)
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def test_fallible_does_not_swallow_base_exceptions() -> None:
|
|
111
|
+
def interrupt() -> Never:
|
|
112
|
+
raise KeyboardInterrupt
|
|
113
|
+
|
|
114
|
+
with pytest.raises(KeyboardInterrupt):
|
|
115
|
+
Fallible(interrupt)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_fallible_only_captures_selected_exceptions() -> None:
|
|
119
|
+
captured = Fallible(lambda: int("not a number"), ValueError)
|
|
120
|
+
failed = captured.maybe_exception()
|
|
121
|
+
assert isinstance(failed, Right)
|
|
122
|
+
assert isinstance(failed.value, ValueError)
|
|
123
|
+
|
|
124
|
+
with pytest.raises(TypeError):
|
|
125
|
+
Fallible(lambda: len(None), ValueError) # type: ignore[arg-type]
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def test_fallible_accepts_and_preserves_a_tuple_of_exception_types() -> None:
|
|
129
|
+
selected = (ValueError, RuntimeError)
|
|
130
|
+
result = Fallible(lambda: 1, selected).map(
|
|
131
|
+
lambda _: (_ for _ in ()).throw(RuntimeError("mapped failure"))
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
failed = result.maybe_exception()
|
|
135
|
+
assert isinstance(failed, Right)
|
|
136
|
+
assert isinstance(failed.value, RuntimeError)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def test_typed_readme_flow() -> None:
|
|
140
|
+
def categorise(number: int) -> Either[Literal["A"], Literal["B"]]:
|
|
141
|
+
if number == 0:
|
|
142
|
+
return Either.new("A")
|
|
143
|
+
return Either.right("B")
|
|
144
|
+
|
|
145
|
+
assert [item.is_left() for item in map(categorise, [0, 1, 0])] == [True, False, True]
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: uogtad
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Typed functional control containers for Python
|
|
5
|
+
Author: uogtad contributors
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/blakehawkins/uogtad
|
|
8
|
+
Project-URL: Issues, https://github.com/blakehawkins/uogtad/issues
|
|
9
|
+
Project-URL: Repository, https://github.com/blakehawkins/uogtad.git
|
|
10
|
+
Keywords: either,functional-programming,maybe,result,typing
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
14
|
+
Classifier: Typing :: Typed
|
|
15
|
+
Requires-Python: >=3.15
|
|
16
|
+
Description-Content-Type: text/markdown
|
|
17
|
+
License-File: LICENSE
|
|
18
|
+
Provides-Extra: test
|
|
19
|
+
Requires-Dist: hypothesis>=6; extra == "test"
|
|
20
|
+
Requires-Dist: pytest>=7; extra == "test"
|
|
21
|
+
Provides-Extra: typecheck
|
|
22
|
+
Requires-Dist: mypy>=1.19; extra == "typecheck"
|
|
23
|
+
Requires-Dist: pyright>=1.1.408; extra == "typecheck"
|
|
24
|
+
Dynamic: license-file
|
|
25
|
+
|
|
26
|
+
# uoɥʇʎd
|
|
27
|
+
|
|
28
|
+
[](https://github.com/blakehawkins/uogtad/actions/workflows/ci.yml)
|
|
29
|
+
[](https://docs.python.org/3.15/)
|
|
30
|
+
[](https://mypy-lang.org/)
|
|
31
|
+
[](https://github.com/microsoft/pyright)
|
|
32
|
+
[](https://opensource.org/license/mit)
|
|
33
|
+
|
|
34
|
+
A functional control library for python in the same vein as io.vavr.control for java.
|
|
35
|
+
|
|
36
|
+
Provides three immutable, typed control containers:
|
|
37
|
+
|
|
38
|
+
```python
|
|
39
|
+
Either.new(value) # Left(value)
|
|
40
|
+
Either.right(error) # Right(error)
|
|
41
|
+
Maybe.new(value) # Some(value), even when value is None
|
|
42
|
+
Maybe.empty() # Empty()
|
|
43
|
+
Maybe.of_optional(value) # Empty() for None, otherwise Some(value)
|
|
44
|
+
Fallible(computation) # captures Exception, but not KeyboardInterrupt/SystemExit
|
|
45
|
+
Fallible(computation, ValueError) # captures only ValueError (and subclasses)
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
Example usage:
|
|
49
|
+
|
|
50
|
+
```python
|
|
51
|
+
from typing import Literal
|
|
52
|
+
|
|
53
|
+
from uogtad import Either, Fallible
|
|
54
|
+
|
|
55
|
+
def raises() -> str:
|
|
56
|
+
raise RuntimeError("tada")
|
|
57
|
+
|
|
58
|
+
tada = Fallible(raises).as_result().swap().map(lambda exc: str(exc.args[0])).narrow().narrow()
|
|
59
|
+
assert tada == "tada"
|
|
60
|
+
|
|
61
|
+
# Unexpected exceptions remain bugs instead of becoming values. A tuple works
|
|
62
|
+
# just like an ``except`` clause when several exception types are expected.
|
|
63
|
+
parsed = Fallible(lambda: int("not a number"), (ValueError, RuntimeError))
|
|
64
|
+
if failure := parsed.maybe_exception():
|
|
65
|
+
# ``failure.value`` is statically narrowed to ValueError | RuntimeError.
|
|
66
|
+
assert isinstance(failure.value, ValueError)
|
|
67
|
+
|
|
68
|
+
def categorise(num: int) -> Either[Literal['A'], Literal['B']]:
|
|
69
|
+
if num == 0:
|
|
70
|
+
return Either.new('A') # Either is left-biased, like Result[T, E].
|
|
71
|
+
return Either.right('B')
|
|
72
|
+
|
|
73
|
+
results = list(map(categorise, [0, 1, 0, 2, 0, 3]))
|
|
74
|
+
assert [result.is_left() for result in results] == [True, False, True, False, True, False]
|
|
75
|
+
|
|
76
|
+
result = categorise(0)
|
|
77
|
+
if left := result.maybe_left():
|
|
78
|
+
# Static checkers narrow `left` to Left[Literal['A']].
|
|
79
|
+
assert left.value == "A"
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
# Ops
|
|
85
|
+
|
|
86
|
+
Install the latest release from PyPI (Python 3.15 or newer):
|
|
87
|
+
|
|
88
|
+
```shell
|
|
89
|
+
python -m pip install uogtad
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Install the current `master` branch directly from GitHub (Python 3.15 or newer)
|
|
93
|
+
with pip:
|
|
94
|
+
|
|
95
|
+
```shell
|
|
96
|
+
python -m pip install "uogtad @ git+https://github.com/blakehawkins/uogtad.git@master"
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
Or add the same PyPI-compatible Git dependency to a Pixi project:
|
|
100
|
+
|
|
101
|
+
```shell
|
|
102
|
+
pixi add --pypi "uogtad @ git+https://github.com/blakehawkins/uogtad.git@master"
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
Run the test suite:
|
|
106
|
+
|
|
107
|
+
```shell
|
|
108
|
+
pixi run python -m pytest
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
Build and validate the PyPI distributions:
|
|
112
|
+
|
|
113
|
+
```shell
|
|
114
|
+
pixi run package
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
### Releases
|
|
118
|
+
|
|
119
|
+
Releases use [Release Please](https://github.com/googleapis/release-please#readme)
|
|
120
|
+
and [PyPI Trusted Publishing](https://docs.pypi.org/trusted-publishers/), so no
|
|
121
|
+
GitHub repository secrets are required.
|
|
122
|
+
|
|
123
|
+
## Comparison with other libraries
|
|
124
|
+
|
|
125
|
+
[`returns`](https://returns.readthedocs.io/) is a broad collection of typed
|
|
126
|
+
functional abstractions, including IO-aware and asynchronous containers. Its
|
|
127
|
+
decorators, point-free helpers, and `flow` utilities encourage building
|
|
128
|
+
annotated function pipelines. Choose it when an application benefits from that
|
|
129
|
+
larger functional-programming ecosystem and composition style.
|
|
130
|
+
|
|
131
|
+
[`Expression`](https://expression.readthedocs.io/) is inspired by F# and
|
|
132
|
+
provides discriminated unions, computation expressions, immutable collections,
|
|
133
|
+
and functional utilities in addition to `Option` and `Result`. Its decorators,
|
|
134
|
+
free functions, and `pipe` helpers support an F#-style pipeline-oriented
|
|
135
|
+
application design. Choose it when those abstractions should shape more of the
|
|
136
|
+
application.
|
|
137
|
+
|
|
138
|
+
`uogtad` deliberately has a smaller scope: `Either`, `Maybe`, and `Fallible`,
|
|
139
|
+
with operations exposed directly as methods. It intentionally avoids
|
|
140
|
+
decorator-driven control flow, free-function combinators, and a pipeline DSL.
|
|
141
|
+
Choose it when ordinary method chaining, Python pattern matching, and a compact
|
|
142
|
+
API are preferable.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
uogtad/__init__.py
|
|
5
|
+
uogtad/either.py
|
|
6
|
+
uogtad/fallible.py
|
|
7
|
+
uogtad/maybe.py
|
|
8
|
+
uogtad/py.typed
|
|
9
|
+
uogtad/test_properties.py
|
|
10
|
+
uogtad/test_uogtad.py
|
|
11
|
+
uogtad.egg-info/PKG-INFO
|
|
12
|
+
uogtad.egg-info/SOURCES.txt
|
|
13
|
+
uogtad.egg-info/dependency_links.txt
|
|
14
|
+
uogtad.egg-info/requires.txt
|
|
15
|
+
uogtad.egg-info/top_level.txt
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
uogtad
|