simple-json-func 0.1.0__py3-none-any.whl
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.
simple_json_func/main.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
import json
|
|
2
|
+
|
|
3
|
+
# Evaluate expressions defined in JSON so configurations can be saved and reused.
|
|
4
|
+
# Registered functions can have side effects; prefer consistent results when
|
|
5
|
+
# evaluating the same configuration more than once.
|
|
6
|
+
class JsonFunc:
|
|
7
|
+
|
|
8
|
+
# Enable built-in functions such as @calc, @if, and @map on root evaluators.
|
|
9
|
+
def __init__(self, is_root:bool, can_echo:bool, print_hook=print):
|
|
10
|
+
self._f_route = dict()
|
|
11
|
+
# Track functions that receive unevaluated arguments.
|
|
12
|
+
# By default, arguments are evaluated before the call.
|
|
13
|
+
# Late calls evaluate their return value unless argument unpacking
|
|
14
|
+
# is also disabled.
|
|
15
|
+
self._late = dict()
|
|
16
|
+
# Pass one argument to these functions, even if the argument is a
|
|
17
|
+
# list or dictionary.
|
|
18
|
+
self._no_fill = dict()
|
|
19
|
+
self._is_root = is_root
|
|
20
|
+
self._can_echo = can_echo # Whether to emit echo output immediately.
|
|
21
|
+
self._echo_history = [] # Recorded echo output.
|
|
22
|
+
# Hook used to emit echo output.
|
|
23
|
+
self._print_hook = print_hook
|
|
24
|
+
if is_root:
|
|
25
|
+
self._f_route["@calc"] = self.calc
|
|
26
|
+
self._f_route["@if"] = self._check_if
|
|
27
|
+
self._f_route["@map"] = self._map
|
|
28
|
+
self._f_route["@static"] = lambda x:x # Identity function.
|
|
29
|
+
self._f_route["@json"] = lambda x:json.dumps(x)
|
|
30
|
+
self._f_route["@echo"] = self._echo
|
|
31
|
+
self._no_fill["@calc"] = True
|
|
32
|
+
self._no_fill["@static"] = True
|
|
33
|
+
self._no_fill["@json"] = True
|
|
34
|
+
self._no_fill["@echo"] = True # Pass the value as a single argument.
|
|
35
|
+
self._late["@calc"] = True
|
|
36
|
+
self._late["@if"] = True
|
|
37
|
+
|
|
38
|
+
# Record the value and send it to the output hook when enabled.
|
|
39
|
+
def _echo(self, v):
|
|
40
|
+
if self._can_echo:
|
|
41
|
+
self._print_hook(str(v), end="", flush=True)
|
|
42
|
+
# Record the text even when immediate output is disabled.
|
|
43
|
+
self._echo_history.append(str(v))
|
|
44
|
+
|
|
45
|
+
# Return the recorded echo entries.
|
|
46
|
+
def get_echo_history(self) -> list:
|
|
47
|
+
return self._echo_history
|
|
48
|
+
|
|
49
|
+
# Optionally emit the recorded text, then clear the history.
|
|
50
|
+
def flush_echo_history(self, show:bool):
|
|
51
|
+
if show:
|
|
52
|
+
self._print_hook("".join(self._echo_history), flush=True)
|
|
53
|
+
self._echo_history = []
|
|
54
|
+
|
|
55
|
+
# Apply the callable to each item in the list.
|
|
56
|
+
def _map(self, func, lis):
|
|
57
|
+
return [
|
|
58
|
+
func(item)
|
|
59
|
+
for item in lis
|
|
60
|
+
]
|
|
61
|
+
|
|
62
|
+
# Import bindings from another evaluator.
|
|
63
|
+
# Use an empty prefix to keep the original names.
|
|
64
|
+
def merge(self, rhs, prefix:str):
|
|
65
|
+
if not isinstance(rhs, JsonFunc):
|
|
66
|
+
raise AssertionError("rhs of JsonFunc.merge should be JsonFunc")
|
|
67
|
+
for item in rhs._f_route:
|
|
68
|
+
self._f_route[prefix + item] = rhs._f_route[item]
|
|
69
|
+
for item in rhs._late:
|
|
70
|
+
self._late[prefix + item] = rhs._late[item]
|
|
71
|
+
for item in rhs._no_fill:
|
|
72
|
+
self._no_fill[prefix + item] = rhs._no_fill[item]
|
|
73
|
+
|
|
74
|
+
# Register a callable and its evaluation options.
|
|
75
|
+
def bind(self, name:str, func, no_fill=False, late=False):
|
|
76
|
+
self._f_route[name] = func
|
|
77
|
+
self._no_fill[name] = no_fill
|
|
78
|
+
self._late[name] = late
|
|
79
|
+
if self._no_fill[name] is not True:
|
|
80
|
+
del self._no_fill[name]
|
|
81
|
+
if self._late[name] is not True:
|
|
82
|
+
del self._late[name]
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
# Enable late evaluation for this name.
|
|
86
|
+
def late(self, name:str):
|
|
87
|
+
self._late[name] = True
|
|
88
|
+
|
|
89
|
+
# Disable late evaluation for this name.
|
|
90
|
+
def unlate(self, name:str):
|
|
91
|
+
self._late[name] = None
|
|
92
|
+
del self._late[name]
|
|
93
|
+
|
|
94
|
+
# List all registered function names.
|
|
95
|
+
def all_f(self) -> list:
|
|
96
|
+
return [
|
|
97
|
+
item for item in self._f_route
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
# List registered function names that use late evaluation.
|
|
101
|
+
def all_late(self) -> list:
|
|
102
|
+
return [
|
|
103
|
+
item
|
|
104
|
+
for item in self._late
|
|
105
|
+
if self._f_route.get(item) is not None
|
|
106
|
+
]
|
|
107
|
+
|
|
108
|
+
# Select a branch without evaluating either branch here.
|
|
109
|
+
def _check_if(self, cond:bool, vt, vf):
|
|
110
|
+
return vt if cond else vf
|
|
111
|
+
|
|
112
|
+
# Evaluate an expression represented by a JSON-compatible Python value.
|
|
113
|
+
def calc(self, r):
|
|
114
|
+
if isinstance(r, list):
|
|
115
|
+
return [
|
|
116
|
+
self.calc(item) for item in r
|
|
117
|
+
]
|
|
118
|
+
elif isinstance(r, dict):
|
|
119
|
+
if r.get("_f") is None: # Recursively evaluate plain object values.
|
|
120
|
+
return {
|
|
121
|
+
item: self.calc(r[item])
|
|
122
|
+
for item in r
|
|
123
|
+
}
|
|
124
|
+
else: # This object refers to a registered function.
|
|
125
|
+
func = r["_f"]
|
|
126
|
+
rfunc = self._f_route[func] # Look up the registered callable.
|
|
127
|
+
if func == "@static": # Preserve the entire expression as-is.
|
|
128
|
+
return r
|
|
129
|
+
if r.get("_c") is None: # Return the callable without invoking it.
|
|
130
|
+
return rfunc
|
|
131
|
+
# Determine when to evaluate the expression.
|
|
132
|
+
if self._late.get(func) is not True:
|
|
133
|
+
# Evaluate the arguments recursively before the call.
|
|
134
|
+
config = self.calc(r["_c"])
|
|
135
|
+
late = False
|
|
136
|
+
else:
|
|
137
|
+
# Keep the arguments unevaluated for the call.
|
|
138
|
+
config = r["_c"]
|
|
139
|
+
late = True
|
|
140
|
+
if self._no_fill.get(func) is True:
|
|
141
|
+
ans = rfunc(config) # Pass one argument without unpacking.
|
|
142
|
+
else:
|
|
143
|
+
if isinstance(config, dict): # Unpack keyword arguments.
|
|
144
|
+
ans = rfunc(**config)
|
|
145
|
+
elif isinstance(config, list): # Unpack positional arguments.
|
|
146
|
+
ans = rfunc(*config)
|
|
147
|
+
else:
|
|
148
|
+
ans = rfunc(config) # Pass one positional argument.
|
|
149
|
+
if late:
|
|
150
|
+
ans = self.calc(ans) # Evaluate the late call's result.
|
|
151
|
+
return ans
|
|
152
|
+
# Return scalar values unchanged.
|
|
153
|
+
else:
|
|
154
|
+
return r
|
|
155
|
+
|
|
156
|
+
if __name__ == "__main__":
|
|
157
|
+
json_func = JsonFunc(is_root=True, can_echo=False)
|
|
158
|
+
# Use @map to apply a callable to every item in a list.
|
|
159
|
+
json_func.calc({
|
|
160
|
+
"_f": "@map", "_c": {
|
|
161
|
+
"func": {
|
|
162
|
+
"_f": "@echo" # Omit _c to get the callable itself.
|
|
163
|
+
},
|
|
164
|
+
"lis": [
|
|
165
|
+
"hello\n",
|
|
166
|
+
"world\n",
|
|
167
|
+
]
|
|
168
|
+
}
|
|
169
|
+
})
|
|
170
|
+
# Use @if to evaluate only the selected branch.
|
|
171
|
+
json_func.calc({
|
|
172
|
+
"_f": "@if", "_c": [
|
|
173
|
+
False,
|
|
174
|
+
{"_f": "@echo", "_c": "do not output this\n"},
|
|
175
|
+
{"_f": "@echo", "_c": "only output this\n"},
|
|
176
|
+
]
|
|
177
|
+
})
|
|
178
|
+
# @static preserves the entire expression without evaluating its contents.
|
|
179
|
+
# @json converts the value to a JSON string if it is serializable.
|
|
180
|
+
json_func.calc({
|
|
181
|
+
"_f": "@echo", "_c": {
|
|
182
|
+
"_f": "@json", "_c": {
|
|
183
|
+
"_f": "@static", "_c": {
|
|
184
|
+
"_f": "this will not output",
|
|
185
|
+
"_c": "this will also not output"
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
})
|
|
190
|
+
# Print and clear the recorded output.
|
|
191
|
+
json_func.flush_echo_history(show=True)
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: simple-json-func
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: a simple way to create json configuration for functions
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Author: GGN_2015
|
|
8
|
+
Author-email: neko@jlulug.org
|
|
9
|
+
Requires-Python: >=3.6
|
|
10
|
+
Classifier: Programming Language :: Python :: 3
|
|
11
|
+
Classifier: Programming Language :: Python :: 3.6
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.7
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# simple_json_func
|
|
23
|
+
|
|
24
|
+
`simple_json_func` is a Python library for evaluating expressions stored as JSON.
|
|
25
|
+
Register Python callables by name, then use JSON objects to call them, pass
|
|
26
|
+
arguments, and compose nested expressions. The library has no third-party
|
|
27
|
+
runtime dependencies.
|
|
28
|
+
|
|
29
|
+
## Installation
|
|
30
|
+
|
|
31
|
+
Use a standard Python installation with `pip`. From the repository root, run:
|
|
32
|
+
|
|
33
|
+
```sh
|
|
34
|
+
python -m pip install .
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
## Quick start
|
|
38
|
+
|
|
39
|
+
```python
|
|
40
|
+
import json
|
|
41
|
+
from operator import add
|
|
42
|
+
|
|
43
|
+
from simple_json_func import JsonFunc
|
|
44
|
+
|
|
45
|
+
evaluator = JsonFunc(is_root=True, can_echo=False)
|
|
46
|
+
evaluator.bind("add", add)
|
|
47
|
+
|
|
48
|
+
expression = json.loads('''
|
|
49
|
+
{
|
|
50
|
+
"_f": "add",
|
|
51
|
+
"_c": [2, {"_f": "add", "_c": [3, 4]}]
|
|
52
|
+
}
|
|
53
|
+
''')
|
|
54
|
+
print(evaluator.calc(expression)) # 9
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
`calc()` takes a decoded Python value. Use `json.loads()` for JSON text or
|
|
58
|
+
`json.load()` for an open JSON file. Use trusted configurations: an expression
|
|
59
|
+
can invoke any callable registered on its evaluator.
|
|
60
|
+
|
|
61
|
+
## Expression format
|
|
62
|
+
|
|
63
|
+
An object with a non-null `_f` refers to a registered function. Its `_c` field
|
|
64
|
+
controls how the function is used:
|
|
65
|
+
|
|
66
|
+
| `_c` value | Default behavior |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| Array | Unpack it as positional arguments; use `[]` for a call with no arguments. |
|
|
69
|
+
| Object | Unpack it as keyword arguments. |
|
|
70
|
+
| Other non-null value | Pass it as one positional argument. |
|
|
71
|
+
| Omitted or `null` | Return the registered callable without invoking it. |
|
|
72
|
+
|
|
73
|
+
Arrays and ordinary objects (those without a non-null `_f`) are evaluated
|
|
74
|
+
recursively. Scalar values pass through unchanged. A reference to an unregistered
|
|
75
|
+
function raises `KeyError`.
|
|
76
|
+
|
|
77
|
+
## Built-in functions
|
|
78
|
+
|
|
79
|
+
Set `is_root=True` to register these functions. With `is_root=False`, the
|
|
80
|
+
evaluator starts with no registered functions.
|
|
81
|
+
|
|
82
|
+
| Function | Behavior |
|
|
83
|
+
| --- | --- |
|
|
84
|
+
| `@calc` | Evaluates the raw `_c` value as an expression. |
|
|
85
|
+
| `@if` | Takes the raw arguments `[cond, vt, vf]` and evaluates only the selected branch. It tests `cond` using Python truthiness without evaluating it as an expression. |
|
|
86
|
+
| `@map` | Takes a callable `func` and a list `lis`, then returns a list of results, one per item. |
|
|
87
|
+
| `@static` | Returns the entire expression object unchanged, including the `@static` wrapper. |
|
|
88
|
+
| `@json` | Evaluates `_c`, then serializes the result to a JSON string with `json.dumps()`. |
|
|
89
|
+
| `@echo` | Evaluates `_c`, records its string representation, and returns `None`. With `can_echo=True`, it also sends the text to `print_hook` (which defaults to `print`). |
|
|
90
|
+
|
|
91
|
+
For example, pass a callable reference to `@map` and use `@if` to skip an unused
|
|
92
|
+
branch. This example reuses `evaluator` from the quick start:
|
|
93
|
+
|
|
94
|
+
```python
|
|
95
|
+
evaluator.bind("double", lambda value: value * 2)
|
|
96
|
+
|
|
97
|
+
result = evaluator.calc({
|
|
98
|
+
"_f": "@if",
|
|
99
|
+
"_c": [
|
|
100
|
+
True,
|
|
101
|
+
{"_f": "@map", "_c": [{"_f": "double"}, [1, 2, 3]]},
|
|
102
|
+
{"_f": "not_registered", "_c": []},
|
|
103
|
+
],
|
|
104
|
+
})
|
|
105
|
+
print(result) # [2, 4, 6]
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
## Registration and output
|
|
109
|
+
|
|
110
|
+
Use `bind(name, func, no_fill=False, late=False)` to register a callable. By
|
|
111
|
+
default, `calc()` evaluates `_c` before calling the function and returns the
|
|
112
|
+
function's result as-is.
|
|
113
|
+
|
|
114
|
+
- `no_fill=True` passes `_c` as a single argument, even when it is an array or an
|
|
115
|
+
object.
|
|
116
|
+
- `late=True` passes raw arguments and evaluates the returned value. With both
|
|
117
|
+
flags enabled, the callable receives the raw `_c` as one argument and its
|
|
118
|
+
return value passes through unchanged.
|
|
119
|
+
- `late(name)` and `unlate(name)` toggle late evaluation for a name. `all_f()`
|
|
120
|
+
lists registered names, and `all_late()` lists registered late-evaluation names.
|
|
121
|
+
- `merge(other, prefix)` imports bindings from another `JsonFunc` instance,
|
|
122
|
+
prepending `prefix` to each name. Use `""` to leave the names unchanged.
|
|
123
|
+
- `get_echo_history()` returns the recorded `@echo` entries, even when immediate
|
|
124
|
+
output is disabled. `flush_echo_history(show=True)` sends the joined entries to
|
|
125
|
+
`print_hook` and clears them. Pass `show=False` to clear them without printing.
|
|
126
|
+
|
|
127
|
+
## License
|
|
128
|
+
|
|
129
|
+
[MIT](LICENSE)
|
|
130
|
+
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
simple_json_func/__init__.py,sha256=I-e-6U-GNQ7wfolPdzFz6v4N1JXDtx_auVTilV6WKjI,62
|
|
2
|
+
simple_json_func/main.py,sha256=2Kl9y1eDM68tX6iS0h7_URNDt94XGZ9Fh9z62OxepaY,7466
|
|
3
|
+
simple_json_func-0.1.0.dist-info/licenses/LICENSE,sha256=gmkEFqkF3KJjRnhXGoLSfX4xXtfPHT1ghq3YgCF7B3w,1086
|
|
4
|
+
simple_json_func-0.1.0.dist-info/METADATA,sha256=BWg10Hgo8J5kq-BdazSah8rsiha8qBhEjJVTcb8X1Io,4749
|
|
5
|
+
simple_json_func-0.1.0.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
|
|
6
|
+
simple_json_func-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 GGN_2015
|
|
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.
|