pythonic-fp-gadgets 2.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.
@@ -0,0 +1,7 @@
1
+ # Minimal version - only add to when necessary
2
+ **/__pycache__/
3
+ dist/
4
+ **/.dmypy.json
5
+ **/.mypy_cache/
6
+ **/.pytest_cache/
7
+ **/.ruff_cache
@@ -0,0 +1,47 @@
1
+ CHANGELOG
2
+ =========
3
+
4
+ PyPI pythonic-fp-gadgets project.
5
+
6
+ Semantic Versioning
7
+ -------------------
8
+
9
+ Strict 3 digit semantic versioning
10
+
11
+ - **MAJOR** version incremented for incompatible API changes
12
+ - **MINOR** version incremented for backward compatible added functionality
13
+ - **PATCH** version incremented for backward compatible bug fixes
14
+
15
+ See `Semantic Versioning 2.0.0 <https://semver.org>`_.
16
+
17
+ Releases and Important Milestones
18
+ ---------------------------------
19
+
20
+ Update - 2025-08-30
21
+ ~~~~~~~~~~~~~~~~~~~
22
+
23
+ Moved for pythonic_fp.gadgets package to a new GitHub repo, pythonic-fp-gadgets.
24
+ Replaced it with the empty Python module ``pythonic_fp.name_claim``.
25
+
26
+ The gadgets package being different from the other namespace packages
27
+ was throwing off my workflow.
28
+
29
+ Update - 2025-08-09
30
+ ~~~~~~~~~~~~~~~~~~~
31
+
32
+ Preparing for upcoming PyPI release for gadgets.
33
+
34
+ - decided to make gadget's pyproject.toml the exemplar for rest of pythonic-fp namespace
35
+ - pythonic_fp.gadget works with previous and next release of singletons
36
+
37
+ PyPI v1.1.0 - 2025-08-02
38
+ ~~~~~~~~~~~~~~~~~~~~~~~~
39
+
40
+ Released pythonic-fp v1.1.0 which contains pythonic_fp.gadgets package.
41
+
42
+ Update - 2025-08-01
43
+ ~~~~~~~~~~~~~~~~~~~
44
+
45
+ Added package pythonic_fp.gadgets to the "name-claim" PyPI project pythonic-fp.
46
+ The gadgets library is for simple, but useful, functions and data structures
47
+ with minimal dependencies.
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,54 @@
1
+ Metadata-Version: 2.4
2
+ Name: pythonic-fp-gadgets
3
+ Version: 2.2.0
4
+ Summary: Simple Gadgets.
5
+ Keywords: gadgets
6
+ Author-email: "Geoffrey R. Scheller" <geoffrey@scheller.com>
7
+ Requires-Python: >=3.13
8
+ Description-Content-Type: text/x-rst
9
+ Classifier: Development Status :: 4 - Beta
10
+ Classifier: Framework :: Pytest
11
+ Classifier: Intended Audience :: Developers
12
+ Classifier: License :: OSI Approved :: Apache Software License
13
+ Classifier: Operating System :: OS Independent
14
+ Classifier: Programming Language :: Python :: 3.13
15
+ Classifier: Typing :: Typed
16
+ License-File: LICENSE
17
+ Requires-Dist: pythonic-fp-sentinels>=2.1.0
18
+ Requires-Dist: pytest>=8.4.1 ; extra == "test"
19
+ Project-URL: Changelog, https://github.com/grscheller/pythonic-fp-gadgets/blob/main/CHANGELOG.rst
20
+ Project-URL: Documentation, https://grscheller.github.io/pythonic-fp/gadgets/development/build/html/releases.html
21
+ Project-URL: Homepage, https://github.com/grscheller/pythonic-fp/blob/main/README.md
22
+ Project-URL: Source, https://github.com/grscheller/pythonic-fp-gadgets
23
+ Provides-Extra: test
24
+
25
+ Pythonic FP - Gadgets
26
+ =====================
27
+
28
+ PyPI project
29
+ `pythonic-fp
30
+ <https://pypi.org/project/pythonic-fp>`_.
31
+
32
+ Library of simple, but useful, data structures with minimal dependencies.
33
+
34
+ - single item box
35
+ - function returning iterator of its arguments
36
+ - find the last common ancestor of two classes
37
+
38
+ This PyPI project is part of of the grscheller
39
+ `pythonic-fp namespace projects
40
+ <https://github.com/grscheller/pythonic-fp/blob/main/README.md>`_
41
+
42
+ Documentation
43
+ -------------
44
+
45
+ Documentation for this project is hosted on
46
+ `GitHub Pages
47
+ <https://grscheller.github.io/pythonic-fp/gadgets/development/build/html>`_.
48
+
49
+ Copyright and License
50
+ ---------------------
51
+
52
+ Copyright (c) 2025 Geoffrey R. Scheller. Licensed under the Apache
53
+ License, Version 2.0. See the LICENSE file for details.
54
+
@@ -0,0 +1,29 @@
1
+ Pythonic FP - Gadgets
2
+ =====================
3
+
4
+ PyPI project
5
+ `pythonic-fp
6
+ <https://pypi.org/project/pythonic-fp>`_.
7
+
8
+ Library of simple, but useful, data structures with minimal dependencies.
9
+
10
+ - single item box
11
+ - function returning iterator of its arguments
12
+ - find the last common ancestor of two classes
13
+
14
+ This PyPI project is part of of the grscheller
15
+ `pythonic-fp namespace projects
16
+ <https://github.com/grscheller/pythonic-fp/blob/main/README.md>`_
17
+
18
+ Documentation
19
+ -------------
20
+
21
+ Documentation for this project is hosted on
22
+ `GitHub Pages
23
+ <https://grscheller.github.io/pythonic-fp/gadgets/development/build/html>`_.
24
+
25
+ Copyright and License
26
+ ---------------------
27
+
28
+ Copyright (c) 2025 Geoffrey R. Scheller. Licensed under the Apache
29
+ License, Version 2.0. See the LICENSE file for details.
@@ -0,0 +1,77 @@
1
+ [project]
2
+ name = "pythonic-fp-gadgets"
3
+ version = "2.2.0"
4
+ readme = "README.rst"
5
+ requires-python = ">=3.13"
6
+ license = { file = "LICENSE" }
7
+ authors = [{ name = "Geoffrey R. Scheller", email = "geoffrey@scheller.com" }]
8
+ keywords = [
9
+ "gadgets",
10
+ ]
11
+ classifiers = [
12
+ "Development Status :: 4 - Beta",
13
+ "Framework :: Pytest",
14
+ "Intended Audience :: Developers",
15
+ "License :: OSI Approved :: Apache Software License",
16
+ "Operating System :: OS Independent",
17
+ "Programming Language :: Python :: 3.13",
18
+ "Typing :: Typed",
19
+ ]
20
+ dependencies = [
21
+ "pythonic-fp-sentinels>=2.1.0",
22
+ ]
23
+ dynamic = ["description"]
24
+
25
+ [project.urls]
26
+ Changelog = "https://github.com/grscheller/pythonic-fp-gadgets/blob/main/CHANGELOG.rst"
27
+ Documentation = "https://grscheller.github.io/pythonic-fp/gadgets/development/build/html/releases.html"
28
+ Homepage = "https://github.com/grscheller/pythonic-fp/blob/main/README.md"
29
+ Source = "https://github.com/grscheller/pythonic-fp-gadgets"
30
+
31
+ [project.optional-dependencies]
32
+ test = [
33
+ "pytest>=8.4.1",
34
+ ]
35
+
36
+ [build-system]
37
+ requires = ["flit_core>=3.12,<4"]
38
+ build-backend = "flit_core.buildapi"
39
+
40
+ [tool.flit.module]
41
+ name = "pythonic_fp.gadgets"
42
+
43
+ [tool.mypy]
44
+ enable_incomplete_feature = "NewGenericSyntax"
45
+ explicit_package_bases = true
46
+ implicit_reexport = false
47
+ local_partial_types = true
48
+ namespace_packages = true
49
+ warn_redundant_casts = true
50
+ warn_return_any = true
51
+ warn_unused_configs = true
52
+
53
+ [tool.pylsp-mypy]
54
+ enabled = true
55
+ live-mode = true
56
+ dmypy = false
57
+ strict = true
58
+ report_progress = true
59
+
60
+ [tool.pytest.ini_options]
61
+ addopts = "-ra"
62
+ consider_namespace_packages = true
63
+ testpaths = ["tests/"]
64
+
65
+ [tool.ruff]
66
+ target-version = "py313"
67
+
68
+ [tool.ruff.lint.flake8-quotes]
69
+ docstring-quotes = "double"
70
+
71
+ [tool.ruff.lint.per-file-ignores]
72
+ "tests/*" = ["C901"]
73
+ "**/*.py" = ["E741"]
74
+
75
+ [tool.ruff.format]
76
+ quote-style = "single"
77
+ docstring-code-line-length = 72
@@ -0,0 +1,33 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Simple Gadgets.
16
+
17
+ Library of simple, but useful, functions and classes with minimal dependencies.
18
+
19
+ +-------------------------------------+-----------------------------------+------------------------------+
20
+ | Gadget | Description | Module |
21
+ +=====================================+===================================+==============================+
22
+ | class ``Box`` | Single item box | ``pythonic_fp.gadgets.box`` |
23
+ +-------------------------------------+-----------------------------------+------------------------------+
24
+ | function ``it`` | Returns iterator of its arguments | ``pythonic_fp.gadgets.it`` |
25
+ +-------------------------------------+-----------------------------------+------------------------------+
26
+ | function ``latest_common_ancestor`` | Find least common base class | ``pythonic_fp.gadgets.lca`` |
27
+ +-------------------------------------+-----------------------------------+------------------------------+
28
+
29
+ """
30
+
31
+ __author__ = 'Geoffrey R. Scheller'
32
+ __copyright__ = 'Copyright (c) 2023-2025 Geoffrey R. Scheller'
33
+ __license__ = 'Apache License 2.0'
@@ -0,0 +1,172 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Class for a stateful container that can hold at most one item."""
16
+
17
+ __all__ = ['Box']
18
+
19
+ from collections.abc import Callable, Iterator
20
+ from typing import ClassVar, cast, Final, Never, overload, TypeVar
21
+ from pythonic_fp.sentinels.flavored import Sentinel
22
+
23
+ T = TypeVar('T')
24
+
25
+
26
+ class Box[T]:
27
+ """Container holding at most one item of a given type.
28
+
29
+ .. note::
30
+
31
+ - ``Box(item: T)``: contains at one item of type ``T``
32
+ - ``Box[T]()``: creates empty container
33
+
34
+ Where type ``T`` is some definite type, which
35
+ could be ``None`` or even ``Never``.
36
+
37
+ .. tip ::
38
+
39
+ ``Box`` objects can be used in Python match statements.
40
+
41
+ """
42
+ __slots__ = ('_item',)
43
+ __match_args__ = ('_item',)
44
+
45
+ _sentinel: Final[ClassVar[Sentinel[str]]] = Sentinel('_Box')
46
+
47
+ @overload
48
+ def __init__(self) -> None: ...
49
+ @overload
50
+ def __init__(self, item: T) -> None: ...
51
+
52
+ def __init__(self, item: T | Sentinel[str] = Sentinel('_Box')) -> None:
53
+ """
54
+ :param item: an "optional" initial contained ``item`` for the ``Box``.
55
+ :returns: New ``Box`` instance.
56
+
57
+ """
58
+ self._item = item
59
+
60
+ def __bool__(self) -> bool:
61
+ return self._item is not Sentinel('_Box')
62
+
63
+ def __iter__(self) -> Iterator[T]:
64
+ if self:
65
+ yield cast(T, self._item)
66
+
67
+ def __repr__(self) -> str:
68
+ if self:
69
+ return 'Box(' + repr(self._item) + ')'
70
+ return 'Box()'
71
+
72
+ def __len__(self) -> int:
73
+ return 1 if self else 0
74
+
75
+ def __eq__(self, other: object) -> bool:
76
+ if not isinstance(other, type(self)):
77
+ return False
78
+
79
+ if self._item is other._item:
80
+ return True
81
+ if self._item == other._item:
82
+ return True
83
+ return False
84
+
85
+ @overload
86
+ def get(self) -> T | Never: ...
87
+ @overload
88
+ def get(self, alt: T) -> T: ...
89
+
90
+ def get(self, alt: T | Sentinel[str] = Sentinel('_Box')) -> T | Never:
91
+ """Return the contained item if it exists, otherwise an alternate item.
92
+
93
+ :param alt: an "optional" item of type ``T`` to return if ``Box`` is empty
94
+ :returns: contents of ``Box``, or an alternate item if given and ``Box`` empty
95
+ :raises ValueError: when an ``alt`` item is not provided but needed
96
+
97
+ """
98
+ if self._item is not self._sentinel:
99
+ return cast(T, self._item)
100
+ if alt is self._sentinel:
101
+ msg = 'Box: get from empty Box with no alternate return item provided'
102
+ raise ValueError(msg)
103
+ return cast(T, alt)
104
+
105
+ def pop(self) -> T | Never:
106
+ """Pop the contained item if ``Box`` is not empty.
107
+
108
+ :returns: item contained in the ``Box``
109
+ :raises: ``ValueError`` if Box is empty
110
+
111
+ """
112
+ if self._item is self._sentinel:
113
+ msg = 'Box: Trying to pop an item from an empty Box'
114
+ raise ValueError(msg)
115
+ popped = cast(T, self._item)
116
+ self._item = self._sentinel
117
+ return popped
118
+
119
+ def push(self, item: T) -> None | Never:
120
+ """Push an item into an empty ``Box``.
121
+
122
+ :param item: Item to push into the empty ``Box``.
123
+ :raises ValueError: If ``Box`` is not empty.
124
+
125
+ """
126
+ if self._item is Sentinel('_Box'):
127
+ self._item = item
128
+ else:
129
+ msg = 'Box: Trying to push an item in a non-empty Box'
130
+ raise ValueError(msg)
131
+ return None
132
+
133
+ def put(self, item: T) -> None:
134
+ """Put an item in the Box. Discard any previous contents."""
135
+ self._item = item
136
+
137
+ def exchange(self, new_item: T) -> T | Never:
138
+ """Exchange an item with what is in the Box.
139
+
140
+ :param ``new_item``: New item to exchange for current item.
141
+ :returns: Original contents of the ``Box``.
142
+ :raises ValueError: If Box is empty.
143
+ """
144
+ if self._item is self._sentinel:
145
+ msg = 'Box: Trying to exchange items from an empty Box'
146
+ raise ValueError(msg)
147
+ popped = cast(T, self._item)
148
+ self._item = new_item
149
+ return popped
150
+
151
+ def map[U](self, f: Callable[[T], U]) -> 'Box[U]':
152
+ """Map function ``f`` over contents. We need to return a new
153
+ instance since the type of Box can change.
154
+
155
+ :param f: mapping function
156
+ :returns: a new instance
157
+
158
+ """
159
+ if self._item is Sentinel('_Box'):
160
+ return Box()
161
+ return Box(f(cast(T, self._item)))
162
+
163
+ def bind[U](self, f: Callable[[T], 'Box[U]']) -> 'Box[U]':
164
+ """Flatmap ``Box`` with function ``f``.
165
+
166
+ :param f: binding function
167
+ :returns: a new instance
168
+
169
+ """
170
+ if self._item is self._sentinel:
171
+ return Box()
172
+ return f(cast(T, self._item))
@@ -0,0 +1,29 @@
1
+ from _typeshed import Incomplete
2
+ from collections.abc import Callable, Iterator
3
+ from typing import Never, TypeVar, overload
4
+
5
+ __all__ = ['Box']
6
+
7
+ T = TypeVar('T')
8
+
9
+ class Box[T]:
10
+ __match_args__: Incomplete
11
+ T = TypeVar('T')
12
+ @overload
13
+ def __init__(self) -> None: ...
14
+ @overload
15
+ def __init__(self, item: T) -> None: ...
16
+ def __bool__(self) -> bool: ...
17
+ def __iter__(self) -> Iterator[T]: ...
18
+ def __len__(self) -> int: ...
19
+ def __eq__(self, other: object) -> bool: ...
20
+ @overload
21
+ def get(self) -> T | Never: ...
22
+ @overload
23
+ def get(self, alt: T) -> T: ...
24
+ def pop(self) -> T | Never: ...
25
+ def push(self, item: T) -> None | Never: ...
26
+ def put(self, item: T) -> None: ...
27
+ def exchange(self, new_item: T) -> T | Never: ...
28
+ def map[U](self, f: Callable[[T], U]) -> Box[U]: ...
29
+ def bind[U](self, f: Callable[[T], 'Box[U]']) -> Box[U]: ...
@@ -0,0 +1,36 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Function which returns an iterator of its arguments."""
16
+
17
+ from collections.abc import Iterator
18
+
19
+ __all__ = ['it']
20
+
21
+
22
+ def it[A](*args: A) -> Iterator[A]:
23
+ """Function returning an iterator of its arguments.
24
+
25
+ .. note::
26
+
27
+ Does not create an object to iterate over.
28
+
29
+ - well, not in the Python world
30
+ - maybe in the C world
31
+
32
+ :param args: Objects to iterate over.
33
+ :returns: An iterator of the arguments.
34
+
35
+ """
36
+ yield from args
@@ -0,0 +1,5 @@
1
+ from collections.abc import Iterator
2
+
3
+ __all__ = ['it']
4
+
5
+ def it[A](*args: A) -> Iterator[A]: ...
@@ -0,0 +1,52 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ """Lastest Common Ancestor of Two Classes."""
16
+
17
+ from inspect import getmro
18
+ from typing import Never
19
+
20
+ __all__ = ['latest_common_ancestor']
21
+
22
+
23
+ def latest_common_ancestor(cls1: type, cls2: type) -> type | Never:
24
+ """Find the least upper bound in the inheritance graph
25
+ of two classes.
26
+
27
+ .. warning::
28
+
29
+ This function can fail with a TypeError. Some error messages
30
+ seen are
31
+
32
+ - multiple bases have instance lay-out conflict
33
+ - type 'bool' is not an acceptable base type
34
+
35
+ This happens frequently when the function is given
36
+ Python builtin types.
37
+
38
+ :param cls1: first class
39
+ :param cls2: second class
40
+ :returns: Least common ancestor base class of ``cls1`` and ``cls2``.
41
+ :raises TypeError: theoretically only from ``inspect.getmto``
42
+
43
+ """
44
+ if issubclass(cls1, cls2):
45
+ return cls2
46
+ if issubclass(cls2, cls1):
47
+ return cls1
48
+
49
+ for common_ancestor in getmro(type('LcaDiamondClass', (cls1, cls2), {})):
50
+ if issubclass(cls1, common_ancestor) and issubclass(cls2, common_ancestor):
51
+ return common_ancestor
52
+ raise TypeError("latest_common_ancestor: no common ancestor found!!!")
@@ -0,0 +1,5 @@
1
+ from typing import Never
2
+
3
+ __all__ = ['latest_common_ancestor']
4
+
5
+ def latest_common_ancestor(cls1: type, cls2: type) -> type | Never: ...
@@ -0,0 +1,94 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from pythonic_fp.gadgets.box import Box
16
+
17
+
18
+ class TestGadgetBox:
19
+ """Functionality testing"""
20
+
21
+ def test_box_unchanged(self) -> None:
22
+ box_init_empty: Box[int] = Box()
23
+ box_init_full = Box(42)
24
+
25
+ if box_init_empty or not box_init_full:
26
+ assert False
27
+
28
+ for ii in box_init_empty:
29
+ assert False
30
+
31
+ for ii in box_init_full:
32
+ assert ii == 42
33
+
34
+ for ii in box_init_empty:
35
+ if ii == 42:
36
+ break
37
+ else:
38
+ assert True
39
+
40
+ for ii in box_init_full:
41
+ if ii == 42:
42
+ break
43
+ else:
44
+ assert False
45
+
46
+ for ii in box_init_full:
47
+ if ii == -1:
48
+ break
49
+ else:
50
+ assert True
51
+
52
+ assert repr(box_init_empty) == 'Box()'
53
+ assert repr(box_init_full) == 'Box(42)'
54
+
55
+ assert len(box_init_empty) == 0
56
+ assert len(box_init_full) == 1
57
+
58
+ assert box_init_empty == box_init_empty
59
+ assert box_init_full == box_init_full
60
+ assert box_init_empty != box_init_full
61
+
62
+ assert box_init_empty.get(-1) == -1
63
+ assert box_init_full.get(-1) == 42
64
+
65
+ try:
66
+ assert box_init_full.get() == 42
67
+ except ValueError:
68
+ assert False
69
+ else:
70
+ assert True
71
+ finally:
72
+ assert True
73
+
74
+ try:
75
+ assert box_init_empty.get() == 42
76
+ except ValueError:
77
+ assert True
78
+ else:
79
+ assert False
80
+ finally:
81
+ assert True
82
+
83
+ assert box_init_full.map(lambda x: x // 2) == Box(21)
84
+ assert box_init_empty.map(lambda x: x // 2) == Box()
85
+ assert box_init_full == Box(42)
86
+ assert box_init_empty == Box()
87
+ assert box_init_full.map(lambda x: str(x)) == Box('42')
88
+ assert box_init_empty.map(lambda x: str(x)) == Box()
89
+
90
+ def f(x: int) -> Box['str']:
91
+ return Box(str(2*x))
92
+
93
+ assert box_init_full.bind(f) == Box('84')
94
+ assert box_init_empty.bind(f) == Box[str]()
@@ -0,0 +1,46 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from pythonic_fp.circulararray.auto import ca, CA
16
+ from pythonic_fp.gadgets.it import it
17
+
18
+ class TestGadgetIt:
19
+ """Functionality testing"""
20
+
21
+ def test_it(self) -> None:
22
+ ref0: list[int] = []
23
+ trg0: list[int] = list(it())
24
+ assert ref0 == trg0
25
+
26
+ ref1 = [1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2046, 4092]
27
+ trg1 = list(it(1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2046, 4092))
28
+ assert ref1 == trg1
29
+
30
+ ref2 = [1, 2, 3]
31
+ trg2 = [*it(1,2,3)]
32
+ assert ref2 == trg2
33
+
34
+ ca_iter = CA((1, 2))
35
+ ca_args = ca(1, 2)
36
+ assert ca_iter == ca_args
37
+
38
+ ca0_ref: CA[int] = ca()
39
+ ca0_trg: CA[int] = CA[int](it())
40
+ assert ca0_ref == ca0_trg
41
+
42
+ ca1_ref: CA[int] = CA((42, 7, 11, 100))
43
+ ca1_trg = CA(it(42, 7, 11, 100))
44
+ ca1_splat1 = ca(*it(42, 7, 11, 100))
45
+ ca1_splat2 = ca(*it(42, 7), *it(11, 100))
46
+ assert ca1_ref == ca1_trg == ca1_splat1 == ca1_splat2
@@ -0,0 +1,114 @@
1
+ # Copyright 2023-2025 Geoffrey R. Scheller
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from pythonic_fp.gadgets.lca import latest_common_ancestor as lca
16
+
17
+ class A1():
18
+ pass
19
+
20
+ class A1B1(A1):
21
+ pass
22
+
23
+ class A1B1C1(A1B1):
24
+ pass
25
+
26
+ class A1B1C2(A1B1):
27
+ pass
28
+
29
+ class A1B2(A1):
30
+ pass
31
+
32
+ class A1B2C1(A1B2):
33
+ pass
34
+
35
+ class A1B2C2(A1B2):
36
+ pass
37
+
38
+ class A2():
39
+ pass
40
+
41
+ class A2B1(A2):
42
+ pass
43
+
44
+ class A2B1C1(A2B1):
45
+ pass
46
+
47
+ class A2B1C2(A2B1):
48
+ pass
49
+
50
+ class A2B2(A2):
51
+ pass
52
+
53
+ class A2B2C1(A2B2):
54
+ pass
55
+
56
+ class A2B2C1D1(A2B2C1):
57
+ pass
58
+
59
+ class A2B2C1D2(A2B2C1):
60
+ pass
61
+
62
+ class A2B2C2(A2B2):
63
+ pass
64
+
65
+ class A2B2C2D1(A2B2C2):
66
+ pass
67
+
68
+ class A2B2C2D2(A2B2C2):
69
+ pass
70
+
71
+ class TestLatestCommonAncestor:
72
+ """Functionality testing"""
73
+
74
+ def test_self(self) -> None:
75
+ assert lca(A1, A1) is A1
76
+ assert lca(A1B1, A1B1) is A1B1
77
+ assert lca(A1B1C1, A1B1C1) is A1B1C1
78
+ assert lca(int, int) is int
79
+ assert lca(bool, bool) is bool
80
+
81
+ def test_linear_descent(self) -> None:
82
+ assert lca(A1, A1B1) is A1
83
+ assert lca(A1B1, A1) is A1
84
+ assert lca(A1B1C1, A1) is A1
85
+ assert lca(A1, A1B1C1) is A1
86
+ assert lca(A1B1C1, A1B1) is A1B1
87
+ assert lca(A1B1, A1B1C1) is A1B1
88
+ assert lca(A1B1C1, A1B1) is A1B1
89
+ assert lca(A1B1, A1B1C1) is A1B1
90
+ assert lca(A1B1C1, A1) is A1
91
+ assert lca(A1, A1B1C1) is A1
92
+ assert lca(A2B2, A2B2C2D2) is A2B2
93
+ assert lca(A2B2C2D2, A2B2) is A2B2
94
+ assert lca(int, object) is object
95
+ assert lca(object, int) is object
96
+ assert lca(int, bool) is int
97
+ assert lca(bool, int) is int
98
+
99
+ def test_nonliear_descent(self) -> None:
100
+ assert lca(A1B1, A1B2) is A1
101
+ assert lca(A1B2, A1B1) is A1
102
+ assert lca(A1B2C1, A1B2C2) is A1B2
103
+ assert lca(A1B2C2, A1B2C1) is A1B2
104
+ assert lca(A1B1C1, A1B2C2) is A1
105
+ assert lca(A1B2C2, A1B1C1) is A1
106
+ assert lca(A1B1C1, A1B2C1) is A1
107
+ assert lca(A1B2C1, A1B1C1) is A1
108
+ assert lca(A2B2C1, A2B2C2D2) is A2B2
109
+ assert lca(A2B2C2D2, A2B2C1) is A2B2
110
+ assert lca(A2B1C1, A2B2C2D2) is A2
111
+ assert lca(A2B2C2D2, A2B1C1) is A2
112
+ assert lca(A1, A2) is object
113
+ assert lca(A2B2C2D2, A1B2C2) is object
114
+ assert lca(A1B2C1, A2B1C1) is object