molty 0.1.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.
- molty-0.1.0/LICENSE +202 -0
- molty-0.1.0/MANIFEST.in +1 -0
- molty-0.1.0/PKG-INFO +371 -0
- molty-0.1.0/README.md +345 -0
- molty-0.1.0/molty/__init__.py +6 -0
- molty-0.1.0/molty/compiler/__init__.py +75 -0
- molty-0.1.0/molty/compiler/cli.py +189 -0
- molty-0.1.0/molty/compiler/emit.py +434 -0
- molty-0.1.0/molty/compiler/rules.py +1027 -0
- molty-0.1.0/molty/compiler/tokens.py +235 -0
- molty-0.1.0/molty/py.typed +0 -0
- molty-0.1.0/molty/runtime.py +716 -0
- molty-0.1.0/molty.egg-info/PKG-INFO +371 -0
- molty-0.1.0/molty.egg-info/SOURCES.txt +25 -0
- molty-0.1.0/molty.egg-info/dependency_links.txt +1 -0
- molty-0.1.0/molty.egg-info/entry_points.txt +2 -0
- molty-0.1.0/molty.egg-info/top_level.txt +1 -0
- molty-0.1.0/pyproject.toml +42 -0
- molty-0.1.0/setup.cfg +4 -0
- molty-0.1.0/tests/helpers.py +74 -0
- molty-0.1.0/tests/test_checked.py +214 -0
- molty-0.1.0/tests/test_concurrency.py +356 -0
- molty-0.1.0/tests/test_passthrough.py +212 -0
- molty-0.1.0/tests/test_scope.py +144 -0
- molty-0.1.0/tests/test_stdlib_superset.py +61 -0
- molty-0.1.0/tests/test_val.py +401 -0
- molty-0.1.0/tests/test_val_params.py +98 -0
molty-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
molty-0.1.0/MANIFEST.in
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
recursive-include tests *.py
|
molty-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,371 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: molty
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: A strict superset of Python that turns common Python traps into compile-time errors.
|
|
5
|
+
Author: Shogo Toda
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Shogo256/molty
|
|
8
|
+
Project-URL: Repository, https://github.com/Shogo256/molty
|
|
9
|
+
Project-URL: Issues, https://github.com/Shogo256/molty/issues
|
|
10
|
+
Keywords: python,superset,transpiler,immutability,concurrency,asyncio,multiprocessing
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Operating System :: POSIX :: Linux
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
19
|
+
Classifier: Topic :: Software Development :: Compilers
|
|
20
|
+
Classifier: Topic :: Software Development :: Quality Assurance
|
|
21
|
+
Classifier: Typing :: Typed
|
|
22
|
+
Requires-Python: >=3.11
|
|
23
|
+
Description-Content-Type: text/markdown
|
|
24
|
+
License-File: LICENSE
|
|
25
|
+
Dynamic: license-file
|
|
26
|
+
|
|
27
|
+
```text
|
|
28
|
+
__ __ ___ _ _______ __
|
|
29
|
+
| \/ |/ _ \| | |_ _\ \ / /
|
|
30
|
+
| |\/| | | | | | | | \ V /
|
|
31
|
+
| | | | |_| | |___| | | |
|
|
32
|
+
|_| |_|\___/|_____|_| |_|
|
|
33
|
+
~~~~~~~~~~~~~~~~~~~~~~~~~~:> Molty
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
# Molty
|
|
37
|
+
|
|
38
|
+
Molty is a strict superset of Python. Every valid Python file is a valid
|
|
39
|
+
Molty file. Molty adds a few keywords that turn everyday Python traps into
|
|
40
|
+
errors at compile time: shared mutable objects, the wrong kind of
|
|
41
|
+
concurrency, and type hints that protect nothing at run time.
|
|
42
|
+
|
|
43
|
+
`moltyc` compiles `app.molty.py` to a plain, readable `app.py` that imports only
|
|
44
|
+
`molty.runtime`. Ordinary type checking is left to mypy and pyright, run on the
|
|
45
|
+
generated file.
|
|
46
|
+
|
|
47
|
+
## The trap, side by side
|
|
48
|
+
|
|
49
|
+
The same file, run as plain Python and compiled by moltyc:
|
|
50
|
+
|
|
51
|
+
```text
|
|
52
|
+
# plain Python # Molty
|
|
53
|
+
def add(item, items: list = []): def add(item, items: list = []):
|
|
54
|
+
items.append(item) items.append(item)
|
|
55
|
+
return items return items
|
|
56
|
+
|
|
57
|
+
print(add(1)) # [1] $ moltyc app.molty.py
|
|
58
|
+
print(add(2)) # [1, 2] <- same list app.molty.py:1:29: warning MOL1004:
|
|
59
|
+
print(add(3)) # [1, 2, 3] default [] of 'items' is created
|
|
60
|
+
once and shared by every call
|
|
61
|
+
# nothing tells you # moltyc tells you before it runs
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
By default moltyc does not change what the code means. The `.py` it writes
|
|
65
|
+
behaves exactly like the source, and the warning tells you about the trap.
|
|
66
|
+
There are two ways to act on it:
|
|
67
|
+
|
|
68
|
+
```python
|
|
69
|
+
def lookup(key, _cache={}): # molty: cache
|
|
70
|
+
... # the sharing is on purpose: no warning
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
```bash
|
|
74
|
+
moltyc --rewrite-defaults app.molty.py # moltyc gives every call a fresh list
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
`--rewrite-defaults` changes the meaning on purpose, and in one way only:
|
|
78
|
+
every call gets a fresh object. With it, moltyc writes:
|
|
79
|
+
|
|
80
|
+
```python
|
|
81
|
+
def add(item, items: list | None = None):
|
|
82
|
+
if items is None: # molty: fresh default on every call
|
|
83
|
+
items = []
|
|
84
|
+
items.append(item)
|
|
85
|
+
return items
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## A superset, checked
|
|
89
|
+
|
|
90
|
+
Every `.py` file in the standard library compiles under moltyc without errors.
|
|
91
|
+
Each one comes out byte for byte the same, apart from the one-line
|
|
92
|
+
generated-file header. We checked 628 files on CPython 3.14 (Ubuntu), and 633,
|
|
93
|
+
686 and 734 files on 3.13, 3.12 and 3.11 (python-build-standalone). To check
|
|
94
|
+
it on your own Python:
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
MOLTY_STDLIB=1 python -m unittest discover -s tests -p test_stdlib_superset.py
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
## Install and run
|
|
101
|
+
|
|
102
|
+
Not on PyPI yet. From a checkout:
|
|
103
|
+
|
|
104
|
+
```bash
|
|
105
|
+
pip install -e .
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
```bash
|
|
109
|
+
moltyc app.molty.py # writes app.py next to it
|
|
110
|
+
moltyc src/ # every *.molty.py under src/
|
|
111
|
+
moltyc app.molty.py -o - # print to stdout
|
|
112
|
+
moltyc app.molty.py --explain # list every rewrite moltyc made
|
|
113
|
+
moltyc app.molty.py --rewrite-defaults # fix mutable defaults instead of warning
|
|
114
|
+
moltyc app.molty.py -q # no success line
|
|
115
|
+
moltyc app.molty.py --force # overwrite an app.py that moltyc did not write
|
|
116
|
+
moltyc --version
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
`moltyc` exits with 1 if any file has errors. Warnings are printed, but the
|
|
120
|
+
`.py` file is still written. At a terminal, each file that compiles gets one
|
|
121
|
+
line on stderr:
|
|
122
|
+
|
|
123
|
+
```text
|
|
124
|
+
~~~~:> app.molty.py -> app.py ok (2 warnings)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
When the output is piped, as in CI, that line is left out, and
|
|
128
|
+
`moltyc --version` prints a plain `moltyc 0.1.0` instead of the logo.
|
|
129
|
+
|
|
130
|
+
moltyc refuses to write a `.py` file, and exits with 1, in these cases:
|
|
131
|
+
|
|
132
|
+
* the file is a symbolic link
|
|
133
|
+
* the file is one of the sources, as with `-o app.molty.py`
|
|
134
|
+
* the file is an existing regular file that moltyc did not generate (`--force`
|
|
135
|
+
overwrites it); `-o /dev/null`, to see only the diagnostics, is fine
|
|
136
|
+
|
|
137
|
+
When moltyc walks a directory, it skips symbolic links, so it never reads
|
|
138
|
+
files outside the tree. A file named on the command line is read even if it
|
|
139
|
+
is a link.
|
|
140
|
+
|
|
141
|
+
moltyc also opens the file with `O_NOFOLLOW`, so a link put in place after the
|
|
142
|
+
checks above cannot redirect the write either. Windows has no `O_NOFOLLOW`;
|
|
143
|
+
there, the check before writing is the only guard.
|
|
144
|
+
|
|
145
|
+
## What Molty adds
|
|
146
|
+
|
|
147
|
+
### `val` and `var`
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
val config = {"host": "localhost", "ports": [8080, 8081]}
|
|
151
|
+
var count = 0
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
* A `val` can never be rebound in its scope (MOL1001). That covers `=`,
|
|
155
|
+
`+=`, `for`, `with ... as`, `import`, `del`, `global` and `nonlocal`.
|
|
156
|
+
* A `val` may be declared once in each branch of an `if`/`elif`/`else` or a
|
|
157
|
+
`match`, since only one of them runs:
|
|
158
|
+
|
|
159
|
+
```python
|
|
160
|
+
if verbose:
|
|
161
|
+
val LEVEL = "debug"
|
|
162
|
+
else:
|
|
163
|
+
val LEVEL = "info"
|
|
164
|
+
```
|
|
165
|
+
* Literals bound to a `val` are frozen at compile time, nested ones
|
|
166
|
+
included: `list` becomes `tuple`, `dict` becomes `MappingProxyType`,
|
|
167
|
+
`set` becomes `frozenset`. The annotation follows, so
|
|
168
|
+
`val xs: list[int] = [1]` becomes `xs: tuple[int, ...] = (1,)`.
|
|
169
|
+
* Changing a frozen `val` in place, as in `PRICES.append(3)` or
|
|
170
|
+
`CONFIG["port"] = 80`, is an error (MOL1005); it would fail at run time
|
|
171
|
+
anyway. So is changing a frozen part of it, as in `CONFIG["db"]["host"] = "y"`,
|
|
172
|
+
and `ROUTES[key].append(x)` when every item of `ROUTES` is a frozen literal.
|
|
173
|
+
A value you build up step by step belongs in a `var`.
|
|
174
|
+
* A `val` bound to any other object, such as `val cache = LRUCache()`, only
|
|
175
|
+
promises not to be rebound. Its methods can be called as usual.
|
|
176
|
+
* `json.dumps` does not accept a frozen dict. Convert it first:
|
|
177
|
+
`json.dumps(dict(config))`.
|
|
178
|
+
* `var` and plain `x = ...` work exactly as in Python.
|
|
179
|
+
|
|
180
|
+
### `val` parameters
|
|
181
|
+
|
|
182
|
+
```python
|
|
183
|
+
def total(items: val list[int]) -> int:
|
|
184
|
+
items.append(0) # MOL1002
|
|
185
|
+
return sum(items)
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
Rebinding a `val` parameter, or calling one of the built-in mutating methods
|
|
189
|
+
of `list`, `dict` and `set` on it (`append`, `update`, `items[k] = v`, `+=`,
|
|
190
|
+
...), is an error. The full list is `MUTATING_METHODS` in
|
|
191
|
+
`molty/compiler/rules.py`. Callers pass the object as usual; nothing is copied.
|
|
192
|
+
|
|
193
|
+
Because the function promises not to change the argument, moltyc widens its
|
|
194
|
+
annotation to the read-only type: `list[int]` becomes `Sequence[int]`,
|
|
195
|
+
`dict[K, V]` becomes `Mapping[K, V]`, and `set[T]` becomes `AbstractSet[T]`.
|
|
196
|
+
Frozen `val` values (a tuple, a `MappingProxyType`, a `frozenset`) can then be
|
|
197
|
+
passed in, and both `@molty.checked` and mypy accept them.
|
|
198
|
+
|
|
199
|
+
### Mutable default arguments
|
|
200
|
+
|
|
201
|
+
A `list`, `dict` or `set` literal, or a call such as `list()` or
|
|
202
|
+
`collections.defaultdict(...)`, used as a default is a MOL1004 warning. The
|
|
203
|
+
code is left alone.
|
|
204
|
+
|
|
205
|
+
* A `# molty: cache` comment on the parameter's line marks the sharing as
|
|
206
|
+
intended. The warning goes away, and the parameter is never rewritten.
|
|
207
|
+
* `moltyc --rewrite-defaults` rewrites each unmarked default to a `None`
|
|
208
|
+
default plus a check in the body, as shown above. `--explain` lists every
|
|
209
|
+
rewrite.
|
|
210
|
+
* It only moves a default whose names are builtins, module-level imports, or
|
|
211
|
+
the loop variables of a comprehension inside the default. Any other name
|
|
212
|
+
would mean something else in the function body: a class attribute is not
|
|
213
|
+
visible there, and a variable would be read at call time instead of when
|
|
214
|
+
`def` ran. Such a default keeps the warning, and so does a default of a
|
|
215
|
+
`lambda`.
|
|
216
|
+
|
|
217
|
+
### `task`, `compute` and `scope`
|
|
218
|
+
|
|
219
|
+
```python
|
|
220
|
+
task def fetch(url: str) -> bytes: ... # I/O-bound: an asyncio coroutine
|
|
221
|
+
compute def digest(data: bytes) -> bytes: ... # CPU-bound: runs in a process pool
|
|
222
|
+
|
|
223
|
+
task def main(urls: list[str]) -> list[bytes]:
|
|
224
|
+
async with scope() as s:
|
|
225
|
+
for url in urls:
|
|
226
|
+
s.spawn(fetch(url))
|
|
227
|
+
pages = s.results() # everything spawned has finished here
|
|
228
|
+
return [await digest(page) for page in pages]
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
* `task def` compiles to `async def`.
|
|
232
|
+
* Calling a `compute` function returns a coroutine that runs the body in a
|
|
233
|
+
shared `ProcessPoolExecutor`, so you can `await` it or `spawn` it.
|
|
234
|
+
* `scope()` wraps `asyncio.TaskGroup`. `s.results()` returns the results in
|
|
235
|
+
spawn order once the block has exited. If one spawned task fails, the
|
|
236
|
+
others are cancelled, the block raises an `ExceptionGroup`, and
|
|
237
|
+
`s.results()` is no longer usable. Partial results have to be collected by
|
|
238
|
+
the tasks themselves.
|
|
239
|
+
* A `compute` that calls a `task` is an error (MOL2001). A `task` that awaits
|
|
240
|
+
a `compute` is fine.
|
|
241
|
+
* A call to a `task` or `compute` whose coroutine never gets run is a warning
|
|
242
|
+
(MOL2006). That covers using the result in an f-string or an expression,
|
|
243
|
+
dropping it, and passing it to an ordinary function such as `print(work(n))`.
|
|
244
|
+
Awaiting it, assigning it, returning it, and passing it to something that
|
|
245
|
+
runs coroutines (`s.spawn`, `asyncio.run`, `asyncio.gather`,
|
|
246
|
+
`asyncio.wait_for`, `create_task`, `run_until_complete`, ...) are fine; to
|
|
247
|
+
hand it to a helper of your own, assign it to a name first. A `compute`
|
|
248
|
+
calling another `compute` is also MOL2006, because a worker process cannot
|
|
249
|
+
await. The check covers functions defined in the same file, called by their
|
|
250
|
+
own name or through a plain alias such as `f = work`.
|
|
251
|
+
* A job that calls `sys.exit()`, or raises an exception the caller cannot
|
|
252
|
+
rebuild (one whose `__init__` takes two arguments, say), fails with
|
|
253
|
+
`molty.runtime.ComputeError` instead. Its message names the original
|
|
254
|
+
exception, and the worker's traceback comes with it. Other jobs are not
|
|
255
|
+
affected, and the caller's program keeps running.
|
|
256
|
+
* If a worker process dies (a crash, `os._exit`, running out of memory), the
|
|
257
|
+
calls in flight fail with `BrokenProcessPool`. The next call starts a fresh
|
|
258
|
+
pool. A failed call is not retried, since it may be the one that crashed.
|
|
259
|
+
* Cancelling a `compute` call, or letting it time out (`asyncio.wait_for`, a
|
|
260
|
+
failing scope), stops the waiting but not the work. The job runs to the end
|
|
261
|
+
and keeps its worker busy, so later `compute` calls can queue behind jobs
|
|
262
|
+
nobody is waiting for any more.
|
|
263
|
+
* For long jobs that must really stop, put `@molty.isolated` on the
|
|
264
|
+
`compute def`. Each call then runs in a process of its own, and cancelling
|
|
265
|
+
or timing out the call kills that process at once, without touching any
|
|
266
|
+
other call. Starting the process costs about 10 ms per call on Linux
|
|
267
|
+
(forkserver) and about 170 ms where only spawn exists, as on Windows. At
|
|
268
|
+
most as many isolated calls run at once as there are CPUs. `@molty.isolated`
|
|
269
|
+
on anything other than a `compute def` is an error (MOL2007).
|
|
270
|
+
|
|
271
|
+
```python
|
|
272
|
+
import molty
|
|
273
|
+
|
|
274
|
+
@molty.isolated
|
|
275
|
+
compute def render(job: Job) -> bytes: ...
|
|
276
|
+
```
|
|
277
|
+
* Arguments and the result of a `compute` must pickle. Types that are
|
|
278
|
+
picklable by their hint (`int`, `str`, `bytes`, containers of them with the
|
|
279
|
+
item types written out, enums, and module-level dataclasses, NamedTuples and
|
|
280
|
+
TypedDicts) are accepted at compile time with no run-time cost. A bare
|
|
281
|
+
`dict` or `list` says nothing about its items, so it is checked at run time. Types that never pickle (`threading.Lock`,
|
|
282
|
+
generators, sockets, ...) are an error (MOL2004). Anything else is checked
|
|
283
|
+
when the call is made, and the result is checked in the worker.
|
|
284
|
+
* Stopped with SIGTERM (the default of `kill`, systemd and Docker), Python
|
|
285
|
+
skips its exit handlers, so the forkserver and idle workers stay behind.
|
|
286
|
+
Turn SIGTERM into a normal exit when the program starts; Ctrl-C needs
|
|
287
|
+
nothing.
|
|
288
|
+
|
|
289
|
+
```python
|
|
290
|
+
import signal, sys
|
|
291
|
+
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
|
|
292
|
+
```
|
|
293
|
+
* A `compute def` must be a plain module-level function (MOL2005), because
|
|
294
|
+
worker processes import it by name. As with any `multiprocessing` code,
|
|
295
|
+
start your program under `if __name__ == "__main__":`, and run it from a
|
|
296
|
+
file. Code fed through stdin or a REPL fails with confusing errors, because
|
|
297
|
+
the workers cannot import the main module.
|
|
298
|
+
* Creating a `threading.Thread` inside a `task` or `compute` is a warning
|
|
299
|
+
(MOL2002), and so is `asyncio.create_task` outside a scope (MOL2003).
|
|
300
|
+
Neither is forbidden.
|
|
301
|
+
|
|
302
|
+
### `@molty.checked`
|
|
303
|
+
|
|
304
|
+
```python
|
|
305
|
+
import molty
|
|
306
|
+
|
|
307
|
+
@molty.checked
|
|
308
|
+
def scale(xs: list[int], factor: float) -> list[float]: ...
|
|
309
|
+
|
|
310
|
+
scale("abc", 2) # CheckError: scale() argument 'xs' must be list, not str
|
|
311
|
+
```
|
|
312
|
+
|
|
313
|
+
Only functions with the decorator are checked. By default the check covers
|
|
314
|
+
the arguments only and is shallow: `list[int]` checks for `list` but not its
|
|
315
|
+
elements. Two options go further, at the cost of more work on every call:
|
|
316
|
+
|
|
317
|
+
```python
|
|
318
|
+
@molty.checked(deep=True) # items of lists, tuples, sets and dicts too
|
|
319
|
+
def load(rows: list[dict[str, int]]) -> None: ...
|
|
320
|
+
# CheckError: load() argument 'rows'[2]['id'] must be int, not str
|
|
321
|
+
|
|
322
|
+
@molty.checked(returns=True) # the return value too
|
|
323
|
+
def name() -> str: ...
|
|
324
|
+
```
|
|
325
|
+
|
|
326
|
+
The check follows `isinstance`, as mypy does, so `True` passes where an
|
|
327
|
+
`int` is expected, and an `int` passes where a `float` is.
|
|
328
|
+
|
|
329
|
+
### `MOLTY_CHECKS=0`
|
|
330
|
+
|
|
331
|
+
This turns off every run-time check: `@molty.checked` returns the function
|
|
332
|
+
unchanged, and `compute` stops checking picklability.
|
|
333
|
+
|
|
334
|
+
## Diagnostics
|
|
335
|
+
|
|
336
|
+
| Code | Kind | Meaning |
|
|
337
|
+
|---------|---------|--------------------------------------------------------------|
|
|
338
|
+
| MOL0001 | error | syntax error |
|
|
339
|
+
| MOL1001 | error | a `val` is rebound |
|
|
340
|
+
| MOL1002 | error | a `val` parameter is rebound or mutated |
|
|
341
|
+
| MOL1003 | error | malformed `val`/`var` declaration (`val x: int` with no value, `val a.b = 1`, ...) |
|
|
342
|
+
| MOL1004 | warning | a mutable default argument, shared by every call |
|
|
343
|
+
| MOL1005 | error | a frozen `val` is changed in place |
|
|
344
|
+
| MOL2001 | error | a `compute` calls a `task` |
|
|
345
|
+
| MOL2002 | warning | `threading.Thread` inside a `task` or `compute` |
|
|
346
|
+
| MOL2003 | warning | `asyncio.create_task` outside `scope()` |
|
|
347
|
+
| MOL2004 | error | a `compute` argument or result cannot be pickled |
|
|
348
|
+
| MOL2005 | error | a `compute def` that is nested, a method, or a generator |
|
|
349
|
+
| MOL2006 | warning | a `task` or `compute` called but not awaited or handed on |
|
|
350
|
+
| MOL2007 | error | `@molty.isolated` on something other than a `compute def` |
|
|
351
|
+
|
|
352
|
+
## Limits of this first version
|
|
353
|
+
|
|
354
|
+
* There is no ownership model. Aliasing a `val` parameter (`other = items;
|
|
355
|
+
other.append(1)`) is not caught.
|
|
356
|
+
* Tested on CPython 3.11, 3.12, 3.13 and 3.14. On 3.11, a `@molty.checked`
|
|
357
|
+
task is checked when it is awaited rather than when it is called, because
|
|
358
|
+
`inspect.markcoroutinefunction` only exists from 3.12.
|
|
359
|
+
|
|
360
|
+
## Development
|
|
361
|
+
|
|
362
|
+
```bash
|
|
363
|
+
python -m unittest discover -s tests
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
The package and the tests use only the standard library. The `molty` package
|
|
367
|
+
passes `mypy --strict`.
|
|
368
|
+
|
|
369
|
+
## License
|
|
370
|
+
|
|
371
|
+
Apache License 2.0. See [LICENSE](LICENSE).
|