python-corekit 0.6.3__py3-none-any.whl → 0.6.4__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.
- corekit/data/__init__.py +6 -0
- corekit/data/arithmetic/__init__.py +97 -0
- corekit/data/arithmetic/expression.py +449 -0
- corekit/data/arithmetic/keys.py +38 -0
- corekit/data/arithmetic/operator.py +44 -0
- corekit/data/expressions/__init__.py +46 -6
- corekit/data/expressions/comparison.py +78 -1
- corekit/data/expressions/expression.py +77 -1
- corekit/data/expressions/keys.py +34 -0
- corekit/data/expressions/operator.py +33 -12
- {python_corekit-0.6.3.dist-info → python_corekit-0.6.4.dist-info}/METADATA +1 -1
- {python_corekit-0.6.3.dist-info → python_corekit-0.6.4.dist-info}/RECORD +15 -10
- {python_corekit-0.6.3.dist-info → python_corekit-0.6.4.dist-info}/WHEEL +0 -0
- {python_corekit-0.6.3.dist-info → python_corekit-0.6.4.dist-info}/licenses/LICENSE +0 -0
- {python_corekit-0.6.3.dist-info → python_corekit-0.6.4.dist-info}/top_level.txt +0 -0
corekit/data/__init__.py
CHANGED
|
@@ -27,6 +27,9 @@ from corekit.data.expressions import (
|
|
|
27
27
|
Dialect,
|
|
28
28
|
Equals,
|
|
29
29
|
Expression,
|
|
30
|
+
ExpressionField,
|
|
31
|
+
ExpressionKey,
|
|
32
|
+
ExpressionType,
|
|
30
33
|
FieldExpression,
|
|
31
34
|
GreaterThan,
|
|
32
35
|
GreaterThanOrEquals,
|
|
@@ -67,6 +70,9 @@ __all__ = [
|
|
|
67
70
|
"DatasetStats",
|
|
68
71
|
"Equals",
|
|
69
72
|
"Expression",
|
|
73
|
+
"ExpressionField",
|
|
74
|
+
"ExpressionKey",
|
|
75
|
+
"ExpressionType",
|
|
70
76
|
"Field",
|
|
71
77
|
"FieldDescription",
|
|
72
78
|
"FieldExpression",
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Composable arithmetic expression trees.
|
|
3
|
+
|
|
4
|
+
Build with ``Field`` / ``Literal`` and operator overloads, evaluate against a
|
|
5
|
+
context, and round-trip with ``to_dict`` / ``from_dict``::
|
|
6
|
+
|
|
7
|
+
from corekit.data.arithmetic import Field
|
|
8
|
+
|
|
9
|
+
total = ((Field("pad_cost") * Field("pad_qty")) + (Field("labor_rate") * Field("hours"))).round()
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from typing import Annotated, Any
|
|
13
|
+
|
|
14
|
+
from pydantic import GetCoreSchemaHandler
|
|
15
|
+
from pydantic_core import core_schema
|
|
16
|
+
|
|
17
|
+
from corekit.data.arithmetic.expression import (
|
|
18
|
+
Abs,
|
|
19
|
+
Add,
|
|
20
|
+
ArithmeticExpression,
|
|
21
|
+
Ceil,
|
|
22
|
+
Divide,
|
|
23
|
+
Field,
|
|
24
|
+
Floor,
|
|
25
|
+
Literal,
|
|
26
|
+
Max,
|
|
27
|
+
Min,
|
|
28
|
+
Modulo,
|
|
29
|
+
Multiply,
|
|
30
|
+
Negate,
|
|
31
|
+
Percent,
|
|
32
|
+
PercentOf,
|
|
33
|
+
Power,
|
|
34
|
+
Round,
|
|
35
|
+
Subtract,
|
|
36
|
+
UnknownArithmeticFieldError,
|
|
37
|
+
coerce,
|
|
38
|
+
)
|
|
39
|
+
from corekit.data.arithmetic.keys import ArithmeticKey, ArithmeticType
|
|
40
|
+
from corekit.data.arithmetic.operator import ArithmeticOperator
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _ArithmeticExpressionPydanticAnnotation:
|
|
44
|
+
"""
|
|
45
|
+
Pydantic marker so ``ArithmeticExpression`` nests in BaseModels.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def __get_pydantic_core_schema__(
|
|
50
|
+
cls,
|
|
51
|
+
_source_type: Any,
|
|
52
|
+
_handler: GetCoreSchemaHandler,
|
|
53
|
+
) -> core_schema.CoreSchema:
|
|
54
|
+
def validate(value: Any) -> ArithmeticExpression:
|
|
55
|
+
if isinstance(value, ArithmeticExpression):
|
|
56
|
+
return value
|
|
57
|
+
if isinstance(value, dict):
|
|
58
|
+
return ArithmeticExpression.from_dict(value)
|
|
59
|
+
raise TypeError(f"Expected ArithmeticExpression or dict, got {type(value)!r}")
|
|
60
|
+
|
|
61
|
+
return core_schema.no_info_plain_validator_function(
|
|
62
|
+
validate,
|
|
63
|
+
serialization=core_schema.plain_serializer_function_ser_schema(
|
|
64
|
+
lambda value: value.to_dict(),
|
|
65
|
+
when_used="always",
|
|
66
|
+
),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
ArithmeticExpressionField = Annotated[ArithmeticExpression, _ArithmeticExpressionPydanticAnnotation]
|
|
71
|
+
|
|
72
|
+
__all__ = [
|
|
73
|
+
"Abs",
|
|
74
|
+
"Add",
|
|
75
|
+
"ArithmeticExpression",
|
|
76
|
+
"ArithmeticExpressionField",
|
|
77
|
+
"ArithmeticKey",
|
|
78
|
+
"ArithmeticOperator",
|
|
79
|
+
"ArithmeticType",
|
|
80
|
+
"Ceil",
|
|
81
|
+
"Divide",
|
|
82
|
+
"Field",
|
|
83
|
+
"Floor",
|
|
84
|
+
"Literal",
|
|
85
|
+
"Max",
|
|
86
|
+
"Min",
|
|
87
|
+
"Modulo",
|
|
88
|
+
"Multiply",
|
|
89
|
+
"Negate",
|
|
90
|
+
"Percent",
|
|
91
|
+
"PercentOf",
|
|
92
|
+
"Power",
|
|
93
|
+
"Round",
|
|
94
|
+
"Subtract",
|
|
95
|
+
"UnknownArithmeticFieldError",
|
|
96
|
+
"coerce",
|
|
97
|
+
]
|
|
@@ -0,0 +1,449 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Composable arithmetic expression trees.
|
|
3
|
+
|
|
4
|
+
Evaluate against a context (mapping / object) to a ``float``. Serialize with
|
|
5
|
+
``to_dict`` / ``from_dict``. Build trees with operator overloads on ``Field`` /
|
|
6
|
+
``Literal``::
|
|
7
|
+
|
|
8
|
+
from corekit.data.arithmetic import Field
|
|
9
|
+
|
|
10
|
+
total = (
|
|
11
|
+
(Field("pad_cost") * Field("pad_qty"))
|
|
12
|
+
+ (Field("labor_rate") * Field("hours"))
|
|
13
|
+
).round()
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import math
|
|
19
|
+
from typing import Any
|
|
20
|
+
|
|
21
|
+
from corekit.data.arithmetic.keys import ArithmeticKey, ArithmeticType
|
|
22
|
+
from corekit.data.arithmetic.operator import ArithmeticOperator
|
|
23
|
+
from corekit.exceptions import InternalCoreException
|
|
24
|
+
from corekit.utils import parse_float
|
|
25
|
+
|
|
26
|
+
UNSET = object()
|
|
27
|
+
_DEFAULT_ROUND_DIGITS = 2
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class UnknownArithmeticFieldError(InternalCoreException):
|
|
31
|
+
"""
|
|
32
|
+
Raised when an arithmetic field names a key the context does not have.
|
|
33
|
+
"""
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class ArithmeticExpression:
|
|
37
|
+
"""
|
|
38
|
+
Base for numeric expression nodes. Subclasses implement ``__call__`` and
|
|
39
|
+
``to_dict``.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
def __call__(self, context: Any = None) -> float:
|
|
43
|
+
raise NotImplementedError
|
|
44
|
+
|
|
45
|
+
def to_dict(self) -> dict[str, Any]:
|
|
46
|
+
raise NotImplementedError
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def from_dict(cls, data: dict[str, Any] | ArithmeticExpression) -> ArithmeticExpression:
|
|
50
|
+
if isinstance(data, ArithmeticExpression):
|
|
51
|
+
return data
|
|
52
|
+
if not isinstance(data, dict):
|
|
53
|
+
raise TypeError(f"ArithmeticExpression.from_dict expected a dict, got {type(data)!r}")
|
|
54
|
+
|
|
55
|
+
kind = data.get(ArithmeticKey.TYPE)
|
|
56
|
+
if kind == ArithmeticType.FIELD:
|
|
57
|
+
return Field.from_dict(data)
|
|
58
|
+
if kind == ArithmeticType.LITERAL:
|
|
59
|
+
return Literal.from_dict(data)
|
|
60
|
+
if kind == ArithmeticType.NEGATE:
|
|
61
|
+
return Negate.from_dict(data)
|
|
62
|
+
if kind == ArithmeticType.ABS:
|
|
63
|
+
return Abs.from_dict(data)
|
|
64
|
+
if kind == ArithmeticType.PERCENT:
|
|
65
|
+
return Percent.from_dict(data)
|
|
66
|
+
if kind == ArithmeticType.ROUND:
|
|
67
|
+
return Round.from_dict(data)
|
|
68
|
+
if kind == ArithmeticType.FLOOR:
|
|
69
|
+
return Floor.from_dict(data)
|
|
70
|
+
if kind == ArithmeticType.CEIL:
|
|
71
|
+
return Ceil.from_dict(data)
|
|
72
|
+
return BinaryOperation.from_dict(data)
|
|
73
|
+
|
|
74
|
+
def __add__(self, other: Any) -> Add:
|
|
75
|
+
return Add(self, coerce(other))
|
|
76
|
+
|
|
77
|
+
def __radd__(self, other: Any) -> Add:
|
|
78
|
+
return Add(coerce(other), self)
|
|
79
|
+
|
|
80
|
+
def __sub__(self, other: Any) -> Subtract:
|
|
81
|
+
return Subtract(self, coerce(other))
|
|
82
|
+
|
|
83
|
+
def __rsub__(self, other: Any) -> Subtract:
|
|
84
|
+
return Subtract(coerce(other), self)
|
|
85
|
+
|
|
86
|
+
def __mul__(self, other: Any) -> Multiply:
|
|
87
|
+
return Multiply(self, coerce(other))
|
|
88
|
+
|
|
89
|
+
def __rmul__(self, other: Any) -> Multiply:
|
|
90
|
+
return Multiply(coerce(other), self)
|
|
91
|
+
|
|
92
|
+
def __truediv__(self, other: Any) -> Divide:
|
|
93
|
+
return Divide(self, coerce(other))
|
|
94
|
+
|
|
95
|
+
def __rtruediv__(self, other: Any) -> Divide:
|
|
96
|
+
return Divide(coerce(other), self)
|
|
97
|
+
|
|
98
|
+
def __mod__(self, other: Any) -> Modulo:
|
|
99
|
+
return Modulo(self, coerce(other))
|
|
100
|
+
|
|
101
|
+
def __rmod__(self, other: Any) -> Modulo:
|
|
102
|
+
return Modulo(coerce(other), self)
|
|
103
|
+
|
|
104
|
+
def __pow__(self, other: Any) -> Power:
|
|
105
|
+
return Power(self, coerce(other))
|
|
106
|
+
|
|
107
|
+
def __rpow__(self, other: Any) -> Power:
|
|
108
|
+
return Power(coerce(other), self)
|
|
109
|
+
|
|
110
|
+
def __neg__(self) -> Negate:
|
|
111
|
+
return Negate(self)
|
|
112
|
+
|
|
113
|
+
def __abs__(self) -> Abs:
|
|
114
|
+
return Abs(self)
|
|
115
|
+
|
|
116
|
+
def min(self, other: Any) -> Min:
|
|
117
|
+
return Min(self, coerce(other))
|
|
118
|
+
|
|
119
|
+
def max(self, other: Any) -> Max:
|
|
120
|
+
return Max(self, coerce(other))
|
|
121
|
+
|
|
122
|
+
def percent_of(self, base: Any) -> PercentOf:
|
|
123
|
+
"""
|
|
124
|
+
``self`` as a percent of ``base`` (e.g. ``Field("rate").percent_of(Field("price"))``).
|
|
125
|
+
"""
|
|
126
|
+
return PercentOf(self, coerce(base))
|
|
127
|
+
|
|
128
|
+
def percent(self) -> Percent:
|
|
129
|
+
"""
|
|
130
|
+
Convert a percentage number to a ratio (``20`` → ``0.2``).
|
|
131
|
+
"""
|
|
132
|
+
return Percent(self)
|
|
133
|
+
|
|
134
|
+
def round(self, digits: int = _DEFAULT_ROUND_DIGITS) -> Round:
|
|
135
|
+
return Round(self, digits=digits)
|
|
136
|
+
|
|
137
|
+
def floor(self, digits: int = _DEFAULT_ROUND_DIGITS) -> Floor:
|
|
138
|
+
return Floor(self, digits=digits)
|
|
139
|
+
|
|
140
|
+
def ceil(self, digits: int = _DEFAULT_ROUND_DIGITS) -> Ceil:
|
|
141
|
+
return Ceil(self, digits=digits)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def coerce(value: Any) -> ArithmeticExpression:
|
|
145
|
+
if isinstance(value, ArithmeticExpression):
|
|
146
|
+
return value
|
|
147
|
+
if isinstance(value, (int, float)) and not isinstance(value, bool):
|
|
148
|
+
return Literal(value)
|
|
149
|
+
raise TypeError(f"Cannot use {type(value)!r} in an arithmetic expression")
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
class Literal(ArithmeticExpression):
|
|
153
|
+
def __init__(self, value: Any) -> None:
|
|
154
|
+
self.value = value
|
|
155
|
+
|
|
156
|
+
def __repr__(self) -> str:
|
|
157
|
+
return f"{self.value!r}"
|
|
158
|
+
|
|
159
|
+
def __call__(self, context: Any = None) -> float:
|
|
160
|
+
parsed = parse_float(self.value)
|
|
161
|
+
if not parsed.success:
|
|
162
|
+
raise ValueError(f"Arithmetic literal must be numeric, got {self.value!r}")
|
|
163
|
+
return parsed.value
|
|
164
|
+
|
|
165
|
+
def to_dict(self) -> dict[str, Any]:
|
|
166
|
+
return {
|
|
167
|
+
ArithmeticKey.TYPE: ArithmeticType.LITERAL,
|
|
168
|
+
ArithmeticKey.VALUE: self.value,
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
@classmethod
|
|
172
|
+
def from_dict(cls, data: dict[str, Any]) -> Literal:
|
|
173
|
+
return cls(data.get(ArithmeticKey.VALUE))
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
class Field(ArithmeticExpression):
|
|
177
|
+
def __init__(self, name: str) -> None:
|
|
178
|
+
self.name = name
|
|
179
|
+
|
|
180
|
+
def __repr__(self) -> str:
|
|
181
|
+
return f"Field({self.name!r})"
|
|
182
|
+
|
|
183
|
+
def __call__(self, context: Any = None) -> float:
|
|
184
|
+
raw = self.resolve(context)
|
|
185
|
+
parsed = parse_float(raw)
|
|
186
|
+
if not parsed.success:
|
|
187
|
+
raise ValueError(f"Arithmetic field {self.name!r} must be numeric, got {raw!r}")
|
|
188
|
+
return parsed.value
|
|
189
|
+
|
|
190
|
+
def resolve(self, context: Any = None) -> Any:
|
|
191
|
+
if context is None:
|
|
192
|
+
raise UnknownArithmeticFieldError(f"No context to resolve field {self.name!r}")
|
|
193
|
+
|
|
194
|
+
getter = getattr(context, "__getitem__", None)
|
|
195
|
+
if getter is not None:
|
|
196
|
+
try:
|
|
197
|
+
return getter(self.name)
|
|
198
|
+
except (KeyError, IndexError, TypeError):
|
|
199
|
+
pass
|
|
200
|
+
|
|
201
|
+
value = getattr(context, self.name, UNSET)
|
|
202
|
+
if value is UNSET:
|
|
203
|
+
raise UnknownArithmeticFieldError(f"{context!r} has no field {self.name!r}")
|
|
204
|
+
return value
|
|
205
|
+
|
|
206
|
+
def to_dict(self) -> dict[str, Any]:
|
|
207
|
+
return {
|
|
208
|
+
ArithmeticKey.TYPE: ArithmeticType.FIELD,
|
|
209
|
+
ArithmeticKey.NAME: self.name,
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
@classmethod
|
|
213
|
+
def from_dict(cls, data: dict[str, Any]) -> Field:
|
|
214
|
+
name = data.get(ArithmeticKey.NAME)
|
|
215
|
+
if not isinstance(name, str) or not name:
|
|
216
|
+
raise ValueError("Arithmetic field requires a non-empty string name")
|
|
217
|
+
return cls(name)
|
|
218
|
+
|
|
219
|
+
|
|
220
|
+
class BinaryOperation(ArithmeticExpression):
|
|
221
|
+
"""
|
|
222
|
+
Base for binary arithmetic nodes. Subclasses set ``operator`` and ``evaluate``.
|
|
223
|
+
"""
|
|
224
|
+
|
|
225
|
+
operator: ArithmeticOperator
|
|
226
|
+
|
|
227
|
+
def __init__(self, left: ArithmeticExpression, right: ArithmeticExpression) -> None:
|
|
228
|
+
self.left = left
|
|
229
|
+
self.right = right
|
|
230
|
+
|
|
231
|
+
def __repr__(self) -> str:
|
|
232
|
+
return f"({self.left!r} {self.operator.symbol} {self.right!r})"
|
|
233
|
+
|
|
234
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
235
|
+
raise NotImplementedError
|
|
236
|
+
|
|
237
|
+
def __call__(self, context: Any = None) -> float:
|
|
238
|
+
return self.evaluate(self.left(context), self.right(context))
|
|
239
|
+
|
|
240
|
+
def to_dict(self) -> dict[str, Any]:
|
|
241
|
+
return {
|
|
242
|
+
ArithmeticKey.TYPE: self.operator.serialized,
|
|
243
|
+
ArithmeticKey.LEFT: self.left.to_dict(),
|
|
244
|
+
ArithmeticKey.RIGHT: self.right.to_dict(),
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
@classmethod
|
|
248
|
+
def from_dict(cls, data: dict[str, Any]) -> BinaryOperation:
|
|
249
|
+
operator = ArithmeticOperator.from_serialized(data[ArithmeticKey.TYPE])
|
|
250
|
+
for subclass in cls.__subclasses__():
|
|
251
|
+
if subclass.operator is operator:
|
|
252
|
+
return subclass(
|
|
253
|
+
ArithmeticExpression.from_dict(data[ArithmeticKey.LEFT]),
|
|
254
|
+
ArithmeticExpression.from_dict(data[ArithmeticKey.RIGHT]),
|
|
255
|
+
)
|
|
256
|
+
raise ValueError(f"No arithmetic class registered for operator {operator!r}")
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
class Add(BinaryOperation):
|
|
260
|
+
operator = ArithmeticOperator.ADD
|
|
261
|
+
|
|
262
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
263
|
+
return left + right
|
|
264
|
+
|
|
265
|
+
|
|
266
|
+
class Subtract(BinaryOperation):
|
|
267
|
+
operator = ArithmeticOperator.SUBTRACT
|
|
268
|
+
|
|
269
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
270
|
+
return left - right
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
class Multiply(BinaryOperation):
|
|
274
|
+
operator = ArithmeticOperator.MULTIPLY
|
|
275
|
+
|
|
276
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
277
|
+
return left * right
|
|
278
|
+
|
|
279
|
+
|
|
280
|
+
class Divide(BinaryOperation):
|
|
281
|
+
operator = ArithmeticOperator.DIVIDE
|
|
282
|
+
|
|
283
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
284
|
+
if right == 0:
|
|
285
|
+
raise ValueError("Division by zero")
|
|
286
|
+
return left / right
|
|
287
|
+
|
|
288
|
+
|
|
289
|
+
class Modulo(BinaryOperation):
|
|
290
|
+
operator = ArithmeticOperator.MODULO
|
|
291
|
+
|
|
292
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
293
|
+
if right == 0:
|
|
294
|
+
raise ValueError("Modulo by zero")
|
|
295
|
+
return left % right
|
|
296
|
+
|
|
297
|
+
|
|
298
|
+
class Power(BinaryOperation):
|
|
299
|
+
operator = ArithmeticOperator.POWER
|
|
300
|
+
|
|
301
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
302
|
+
return left**right
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
class Min(BinaryOperation):
|
|
306
|
+
operator = ArithmeticOperator.MIN
|
|
307
|
+
|
|
308
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
309
|
+
return min(left, right)
|
|
310
|
+
|
|
311
|
+
|
|
312
|
+
class Max(BinaryOperation):
|
|
313
|
+
operator = ArithmeticOperator.MAX
|
|
314
|
+
|
|
315
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
316
|
+
return max(left, right)
|
|
317
|
+
|
|
318
|
+
|
|
319
|
+
class PercentOf(BinaryOperation):
|
|
320
|
+
"""
|
|
321
|
+
``left`` percent of ``right`` → ``right * left / 100``.
|
|
322
|
+
"""
|
|
323
|
+
|
|
324
|
+
operator = ArithmeticOperator.PERCENT_OF
|
|
325
|
+
|
|
326
|
+
def evaluate(self, left: float, right: float) -> float:
|
|
327
|
+
return right * left / 100.0
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
class UnaryOperation(ArithmeticExpression):
|
|
331
|
+
type_tag: ArithmeticType
|
|
332
|
+
|
|
333
|
+
def __init__(self, expr: ArithmeticExpression) -> None:
|
|
334
|
+
self.expr = expr
|
|
335
|
+
|
|
336
|
+
def evaluate(self, value: float) -> float:
|
|
337
|
+
raise NotImplementedError
|
|
338
|
+
|
|
339
|
+
def __call__(self, context: Any = None) -> float:
|
|
340
|
+
return self.evaluate(self.expr(context))
|
|
341
|
+
|
|
342
|
+
def to_dict(self) -> dict[str, Any]:
|
|
343
|
+
return {
|
|
344
|
+
ArithmeticKey.TYPE: self.type_tag,
|
|
345
|
+
ArithmeticKey.EXPR: self.expr.to_dict(),
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
@classmethod
|
|
349
|
+
def from_dict(cls, data: dict[str, Any]) -> UnaryOperation:
|
|
350
|
+
return cls(ArithmeticExpression.from_dict(data[ArithmeticKey.EXPR]))
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class Negate(UnaryOperation):
|
|
354
|
+
type_tag = ArithmeticType.NEGATE
|
|
355
|
+
|
|
356
|
+
def __repr__(self) -> str:
|
|
357
|
+
return f"-{self.expr!r}"
|
|
358
|
+
|
|
359
|
+
def evaluate(self, value: float) -> float:
|
|
360
|
+
return -value
|
|
361
|
+
|
|
362
|
+
|
|
363
|
+
class Abs(UnaryOperation):
|
|
364
|
+
type_tag = ArithmeticType.ABS
|
|
365
|
+
|
|
366
|
+
def __repr__(self) -> str:
|
|
367
|
+
return f"abs({self.expr!r})"
|
|
368
|
+
|
|
369
|
+
def evaluate(self, value: float) -> float:
|
|
370
|
+
return abs(value)
|
|
371
|
+
|
|
372
|
+
|
|
373
|
+
class Percent(UnaryOperation):
|
|
374
|
+
"""
|
|
375
|
+
Convert a percentage number to a ratio (``20`` → ``0.2``).
|
|
376
|
+
"""
|
|
377
|
+
|
|
378
|
+
type_tag = ArithmeticType.PERCENT
|
|
379
|
+
|
|
380
|
+
def __repr__(self) -> str:
|
|
381
|
+
return f"percent({self.expr!r})"
|
|
382
|
+
|
|
383
|
+
def evaluate(self, value: float) -> float:
|
|
384
|
+
return value / 100.0
|
|
385
|
+
|
|
386
|
+
|
|
387
|
+
class RoundedOperation(ArithmeticExpression):
|
|
388
|
+
"""
|
|
389
|
+
Round / floor / ceil to a fixed number of decimal places (default 2).
|
|
390
|
+
"""
|
|
391
|
+
|
|
392
|
+
type_tag: ArithmeticType
|
|
393
|
+
|
|
394
|
+
def __init__(self, expr: ArithmeticExpression, digits: int = _DEFAULT_ROUND_DIGITS) -> None:
|
|
395
|
+
self.expr = expr
|
|
396
|
+
self.digits = int(digits)
|
|
397
|
+
|
|
398
|
+
def apply(self, value: float) -> float:
|
|
399
|
+
raise NotImplementedError
|
|
400
|
+
|
|
401
|
+
def scale(self) -> float:
|
|
402
|
+
return 10.0**self.digits
|
|
403
|
+
|
|
404
|
+
def __call__(self, context: Any = None) -> float:
|
|
405
|
+
return self.apply(self.expr(context))
|
|
406
|
+
|
|
407
|
+
def to_dict(self) -> dict[str, Any]:
|
|
408
|
+
return {
|
|
409
|
+
ArithmeticKey.TYPE: self.type_tag,
|
|
410
|
+
ArithmeticKey.EXPR: self.expr.to_dict(),
|
|
411
|
+
ArithmeticKey.DIGITS: self.digits,
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
@classmethod
|
|
415
|
+
def from_dict(cls, data: dict[str, Any]) -> RoundedOperation:
|
|
416
|
+
digits = data.get(ArithmeticKey.DIGITS, _DEFAULT_ROUND_DIGITS)
|
|
417
|
+
return cls(ArithmeticExpression.from_dict(data[ArithmeticKey.EXPR]), digits=int(digits))
|
|
418
|
+
|
|
419
|
+
|
|
420
|
+
class Round(RoundedOperation):
|
|
421
|
+
type_tag = ArithmeticType.ROUND
|
|
422
|
+
|
|
423
|
+
def __repr__(self) -> str:
|
|
424
|
+
return f"round({self.expr!r}, {self.digits})"
|
|
425
|
+
|
|
426
|
+
def apply(self, value: float) -> float:
|
|
427
|
+
return round(value, self.digits)
|
|
428
|
+
|
|
429
|
+
|
|
430
|
+
class Floor(RoundedOperation):
|
|
431
|
+
type_tag = ArithmeticType.FLOOR
|
|
432
|
+
|
|
433
|
+
def __repr__(self) -> str:
|
|
434
|
+
return f"floor({self.expr!r}, {self.digits})"
|
|
435
|
+
|
|
436
|
+
def apply(self, value: float) -> float:
|
|
437
|
+
factor = self.scale()
|
|
438
|
+
return math.floor(value * factor) / factor
|
|
439
|
+
|
|
440
|
+
|
|
441
|
+
class Ceil(RoundedOperation):
|
|
442
|
+
type_tag = ArithmeticType.CEIL
|
|
443
|
+
|
|
444
|
+
def __repr__(self) -> str:
|
|
445
|
+
return f"ceil({self.expr!r}, {self.digits})"
|
|
446
|
+
|
|
447
|
+
def apply(self, value: float) -> float:
|
|
448
|
+
factor = self.scale()
|
|
449
|
+
return math.ceil(value * factor) / factor
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Stable serialization tags and dict keys for arithmetic expression trees.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from corekit.schemas.enum import StringEnum
|
|
6
|
+
|
|
7
|
+
__all__ = ["ArithmeticKey", "ArithmeticType"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ArithmeticType(StringEnum):
|
|
11
|
+
"""
|
|
12
|
+
Node kind for non-binary arithmetic nodes.
|
|
13
|
+
|
|
14
|
+
Binary ops use ``ArithmeticOperator.serialized`` instead.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
FIELD = "field"
|
|
18
|
+
LITERAL = "literal"
|
|
19
|
+
NEGATE = "negate"
|
|
20
|
+
ABS = "abs"
|
|
21
|
+
PERCENT = "percent"
|
|
22
|
+
ROUND = "round"
|
|
23
|
+
FLOOR = "floor"
|
|
24
|
+
CEIL = "ceil"
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class ArithmeticKey(StringEnum):
|
|
28
|
+
"""
|
|
29
|
+
Dict keys used by ``ArithmeticExpression.to_dict`` / ``from_dict``.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
TYPE = "type"
|
|
33
|
+
LEFT = "left"
|
|
34
|
+
RIGHT = "right"
|
|
35
|
+
EXPR = "expr"
|
|
36
|
+
NAME = "name"
|
|
37
|
+
VALUE = "value"
|
|
38
|
+
DIGITS = "digits"
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Binary arithmetic operators.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from corekit.data.expressions.operator import Dialect
|
|
6
|
+
from corekit.schemas.enum import ValidatingEnum
|
|
7
|
+
|
|
8
|
+
__all__ = ["ArithmeticOperator"]
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class ArithmeticOperator(ValidatingEnum):
|
|
12
|
+
"""
|
|
13
|
+
A binary arithmetic operator, identified by the node class that uses it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
ADD = Dialect("+", "add")
|
|
17
|
+
SUBTRACT = Dialect("-", "subtract")
|
|
18
|
+
MULTIPLY = Dialect("*", "multiply")
|
|
19
|
+
DIVIDE = Dialect("/", "divide")
|
|
20
|
+
MODULO = Dialect("%", "modulo")
|
|
21
|
+
POWER = Dialect("**", "power")
|
|
22
|
+
MIN = Dialect("min", "min")
|
|
23
|
+
MAX = Dialect("max", "max")
|
|
24
|
+
PERCENT_OF = Dialect("% of", "percent_of")
|
|
25
|
+
|
|
26
|
+
@property
|
|
27
|
+
def symbol(self) -> str:
|
|
28
|
+
return self.value.symbol
|
|
29
|
+
|
|
30
|
+
@property
|
|
31
|
+
def serialized(self) -> str:
|
|
32
|
+
"""
|
|
33
|
+
Stable type tag for ``to_dict`` / ``from_dict`` (``Dialect.name``).
|
|
34
|
+
|
|
35
|
+
Named ``serialized`` so it does not shadow ``Enum.name``.
|
|
36
|
+
"""
|
|
37
|
+
return self.value.name
|
|
38
|
+
|
|
39
|
+
@classmethod
|
|
40
|
+
def from_serialized(cls, name: str) -> "ArithmeticOperator":
|
|
41
|
+
for member in cls:
|
|
42
|
+
if member.serialized == name:
|
|
43
|
+
return member
|
|
44
|
+
raise ValueError(f"Unknown arithmetic operator serialization {name!r}")
|
|
@@ -8,11 +8,17 @@ values or against each other::
|
|
|
8
8
|
Field("first_name") == Field("nickname")
|
|
9
9
|
(Field("age") > 20) & ~Field("name").contains("test")
|
|
10
10
|
|
|
11
|
-
A node evaluates against a record in Python. ``to_sqlalchemy``
|
|
12
|
-
|
|
13
|
-
are refused
|
|
11
|
+
A node evaluates against a record in Python. ``to_sqlalchemy`` and ``to_dict`` /
|
|
12
|
+
``from_dict`` are the other faces of the same tree. Operators SQL cannot mean
|
|
13
|
+
the same way are refused in ``to_sqlalchemy`` rather than compiled into a
|
|
14
|
+
different query.
|
|
14
15
|
"""
|
|
15
16
|
|
|
17
|
+
from typing import Annotated, Any
|
|
18
|
+
|
|
19
|
+
from pydantic import GetCoreSchemaHandler
|
|
20
|
+
from pydantic_core import core_schema
|
|
21
|
+
|
|
16
22
|
from corekit.data.expressions.comparison import (
|
|
17
23
|
Comparison,
|
|
18
24
|
Contains,
|
|
@@ -29,16 +35,51 @@ from corekit.data.expressions.comparison import (
|
|
|
29
35
|
ValueExpression,
|
|
30
36
|
)
|
|
31
37
|
from corekit.data.expressions.expression import And, Expression, Not, Or
|
|
38
|
+
from corekit.data.expressions.keys import ExpressionKey, ExpressionType
|
|
32
39
|
from corekit.data.expressions.operator import Dialect, Operator
|
|
33
40
|
from corekit.data.expressions.target import Target
|
|
34
41
|
|
|
42
|
+
|
|
43
|
+
class _ExpressionPydanticAnnotation:
|
|
44
|
+
"""
|
|
45
|
+
Pydantic marker so ``Expression`` nests in BaseModels via to_dict/from_dict.
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
@classmethod
|
|
49
|
+
def __get_pydantic_core_schema__(
|
|
50
|
+
cls,
|
|
51
|
+
_source_type: Any,
|
|
52
|
+
_handler: GetCoreSchemaHandler,
|
|
53
|
+
) -> core_schema.CoreSchema:
|
|
54
|
+
def validate(value: Any) -> Expression:
|
|
55
|
+
if isinstance(value, Expression):
|
|
56
|
+
return value
|
|
57
|
+
if isinstance(value, dict):
|
|
58
|
+
return Expression.from_dict(value)
|
|
59
|
+
raise TypeError(f"Expected Expression or dict, got {type(value)!r}")
|
|
60
|
+
|
|
61
|
+
return core_schema.no_info_plain_validator_function(
|
|
62
|
+
validate,
|
|
63
|
+
serialization=core_schema.plain_serializer_function_ser_schema(
|
|
64
|
+
lambda value: value.to_dict(),
|
|
65
|
+
when_used="always",
|
|
66
|
+
),
|
|
67
|
+
)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
ExpressionField = Annotated[Expression, _ExpressionPydanticAnnotation]
|
|
71
|
+
|
|
35
72
|
__all__ = [
|
|
36
73
|
"And",
|
|
37
74
|
"Comparison",
|
|
38
75
|
"Contains",
|
|
76
|
+
"Dialect",
|
|
39
77
|
"Equals",
|
|
40
|
-
"IContains",
|
|
41
78
|
"Expression",
|
|
79
|
+
"ExpressionField",
|
|
80
|
+
"ExpressionKey",
|
|
81
|
+
"ExpressionType",
|
|
82
|
+
"IContains",
|
|
42
83
|
"FieldExpression",
|
|
43
84
|
"GreaterThan",
|
|
44
85
|
"GreaterThanOrEquals",
|
|
@@ -48,9 +89,8 @@ __all__ = [
|
|
|
48
89
|
"Not",
|
|
49
90
|
"NotEquals",
|
|
50
91
|
"UnknownFieldError",
|
|
51
|
-
"Or",
|
|
52
|
-
"Dialect",
|
|
53
92
|
"Operator",
|
|
93
|
+
"Or",
|
|
54
94
|
"Target",
|
|
55
95
|
"ValueExpression",
|
|
56
96
|
]
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from typing import Any, Iterable
|
|
2
2
|
|
|
3
|
-
from corekit.data.expressions.expression import Expression
|
|
3
|
+
from corekit.data.expressions.expression import _FROM_DICT_LOADERS, Expression
|
|
4
|
+
from corekit.data.expressions.keys import ExpressionKey, ExpressionType
|
|
4
5
|
from corekit.data.expressions.operator import Operator
|
|
5
6
|
from corekit.data.expressions.target import Target
|
|
6
7
|
|
|
@@ -77,6 +78,50 @@ class Comparison(Expression):
|
|
|
77
78
|
"""
|
|
78
79
|
raise NotImplementedError(f"SQL cannot express `{self.symbol}`: {reason}")
|
|
79
80
|
|
|
81
|
+
def to_dict(self) -> dict[str, Any]:
|
|
82
|
+
return {
|
|
83
|
+
ExpressionKey.TYPE: self.operator.serialized,
|
|
84
|
+
ExpressionKey.LEFT: self._operand_to_dict(self.left),
|
|
85
|
+
ExpressionKey.RIGHT: self._operand_to_dict(self.right),
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
@classmethod
|
|
89
|
+
def from_dict(cls, data: dict[str, Any]) -> "Comparison":
|
|
90
|
+
operator = Operator.from_serialized(data[ExpressionKey.TYPE])
|
|
91
|
+
for subclass in cls.__subclasses__():
|
|
92
|
+
if subclass.operator is operator:
|
|
93
|
+
left = cls._operand_from_dict(data[ExpressionKey.LEFT])
|
|
94
|
+
right = cls._operand_from_dict(data[ExpressionKey.RIGHT])
|
|
95
|
+
if subclass is IsIn and isinstance(right, list):
|
|
96
|
+
right = frozenset(right)
|
|
97
|
+
return subclass(left, right)
|
|
98
|
+
raise ValueError(f"No comparison class registered for operator {operator!r}")
|
|
99
|
+
|
|
100
|
+
@staticmethod
|
|
101
|
+
def _operand_to_dict(value: Any) -> dict[str, Any]:
|
|
102
|
+
if isinstance(value, Expression):
|
|
103
|
+
return value.to_dict()
|
|
104
|
+
if isinstance(value, (set, frozenset)):
|
|
105
|
+
return {
|
|
106
|
+
ExpressionKey.TYPE: ExpressionType.LITERAL,
|
|
107
|
+
ExpressionKey.VALUE: sorted(value, key=repr),
|
|
108
|
+
}
|
|
109
|
+
return {
|
|
110
|
+
ExpressionKey.TYPE: ExpressionType.LITERAL,
|
|
111
|
+
ExpressionKey.VALUE: value,
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
@staticmethod
|
|
115
|
+
def _operand_from_dict(data: dict[str, Any]) -> Any:
|
|
116
|
+
if not isinstance(data, dict):
|
|
117
|
+
raise TypeError(f"Comparison operand must be a dict, got {type(data)!r}")
|
|
118
|
+
kind = data.get(ExpressionKey.TYPE)
|
|
119
|
+
if kind == ExpressionType.FIELD:
|
|
120
|
+
return FieldExpression.from_dict(data)
|
|
121
|
+
if kind == ExpressionType.LITERAL:
|
|
122
|
+
return data.get(ExpressionKey.VALUE)
|
|
123
|
+
raise ValueError(f"Unknown comparison operand type {kind!r}")
|
|
124
|
+
|
|
80
125
|
|
|
81
126
|
class Equals(Comparison):
|
|
82
127
|
operator = Operator.EQUALS
|
|
@@ -260,6 +305,19 @@ class ValueExpression(Expression):
|
|
|
260
305
|
"""
|
|
261
306
|
return self.value
|
|
262
307
|
|
|
308
|
+
def to_dict(self) -> dict[str, Any]:
|
|
309
|
+
value = self.value
|
|
310
|
+
if isinstance(value, (set, frozenset)):
|
|
311
|
+
value = sorted(value, key=repr)
|
|
312
|
+
return {
|
|
313
|
+
ExpressionKey.TYPE: ExpressionType.LITERAL,
|
|
314
|
+
ExpressionKey.VALUE: value,
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
@classmethod
|
|
318
|
+
def from_dict(cls, data: dict[str, Any]) -> "ValueExpression":
|
|
319
|
+
return cls(data.get(ExpressionKey.VALUE))
|
|
320
|
+
|
|
263
321
|
|
|
264
322
|
class FieldExpression(ValueExpression):
|
|
265
323
|
"""
|
|
@@ -300,3 +358,22 @@ class FieldExpression(ValueExpression):
|
|
|
300
358
|
if value is UNSET:
|
|
301
359
|
raise UnknownFieldError(f"{context!r} has no field {self.value!r}")
|
|
302
360
|
return value
|
|
361
|
+
|
|
362
|
+
def to_dict(self) -> dict[str, Any]:
|
|
363
|
+
return {
|
|
364
|
+
ExpressionKey.TYPE: ExpressionType.FIELD,
|
|
365
|
+
ExpressionKey.NAME: self.value,
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
@classmethod
|
|
369
|
+
def from_dict(cls, data: dict[str, Any]) -> "FieldExpression":
|
|
370
|
+
name = data.get(ExpressionKey.NAME)
|
|
371
|
+
if not isinstance(name, str) or not name:
|
|
372
|
+
raise ValueError("Field expression requires a non-empty string name")
|
|
373
|
+
return cls(name)
|
|
374
|
+
|
|
375
|
+
|
|
376
|
+
_FROM_DICT_LOADERS[ExpressionType.FIELD] = FieldExpression.from_dict
|
|
377
|
+
_FROM_DICT_LOADERS[ExpressionType.LITERAL] = ValueExpression.from_dict
|
|
378
|
+
for _operator in Operator:
|
|
379
|
+
_FROM_DICT_LOADERS[_operator.serialized] = Comparison.from_dict
|
|
@@ -1,9 +1,18 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from collections.abc import Callable
|
|
1
4
|
from typing import Any
|
|
2
5
|
|
|
6
|
+
from corekit.data.expressions.keys import ExpressionKey, ExpressionType
|
|
7
|
+
|
|
8
|
+
# Filled by comparison.py at import time so from_dict needs no nested imports.
|
|
9
|
+
_FROM_DICT_LOADERS: dict[str, Callable[[dict[str, Any]], Expression]] = {}
|
|
10
|
+
|
|
3
11
|
|
|
4
12
|
class Expression:
|
|
5
13
|
"""
|
|
6
|
-
Base class for composable predicates. Subclasses implement __call__
|
|
14
|
+
Base class for composable predicates. Subclasses implement __call__,
|
|
15
|
+
``to_sqlalchemy``, and ``to_dict``.
|
|
7
16
|
"""
|
|
8
17
|
|
|
9
18
|
def __call__(self, *args: Any, **kwargs: Any) -> bool:
|
|
@@ -26,6 +35,35 @@ class Expression:
|
|
|
26
35
|
"""
|
|
27
36
|
raise NotImplementedError
|
|
28
37
|
|
|
38
|
+
def to_dict(self) -> dict[str, Any]:
|
|
39
|
+
"""
|
|
40
|
+
JSON-safe encoding of this node (and its children).
|
|
41
|
+
"""
|
|
42
|
+
raise NotImplementedError
|
|
43
|
+
|
|
44
|
+
@classmethod
|
|
45
|
+
def from_dict(cls, data: dict[str, Any] | "Expression") -> "Expression":
|
|
46
|
+
"""
|
|
47
|
+
Rebuild an expression tree from ``to_dict`` output.
|
|
48
|
+
"""
|
|
49
|
+
if isinstance(data, Expression):
|
|
50
|
+
return data
|
|
51
|
+
if not isinstance(data, dict):
|
|
52
|
+
raise TypeError(f"Expression.from_dict expected a dict, got {type(data)!r}")
|
|
53
|
+
|
|
54
|
+
kind = data.get(ExpressionKey.TYPE)
|
|
55
|
+
if kind == ExpressionType.AND:
|
|
56
|
+
return And.from_dict(data)
|
|
57
|
+
if kind == ExpressionType.OR:
|
|
58
|
+
return Or.from_dict(data)
|
|
59
|
+
if kind == ExpressionType.NOT:
|
|
60
|
+
return Not.from_dict(data)
|
|
61
|
+
|
|
62
|
+
loader = _FROM_DICT_LOADERS.get(kind) if isinstance(kind, str) else None
|
|
63
|
+
if loader is not None:
|
|
64
|
+
return loader(data)
|
|
65
|
+
raise ValueError(f"Unknown expression type {kind!r}")
|
|
66
|
+
|
|
29
67
|
|
|
30
68
|
class And(Expression):
|
|
31
69
|
def __init__(self, left: Expression, right: Expression) -> None:
|
|
@@ -41,6 +79,20 @@ class And(Expression):
|
|
|
41
79
|
def to_sqlalchemy(self, context: Any) -> Any:
|
|
42
80
|
return self.left.to_sqlalchemy(context) & self.right.to_sqlalchemy(context)
|
|
43
81
|
|
|
82
|
+
def to_dict(self) -> dict[str, Any]:
|
|
83
|
+
return {
|
|
84
|
+
ExpressionKey.TYPE: ExpressionType.AND,
|
|
85
|
+
ExpressionKey.LEFT: self.left.to_dict(),
|
|
86
|
+
ExpressionKey.RIGHT: self.right.to_dict(),
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
@classmethod
|
|
90
|
+
def from_dict(cls, data: dict[str, Any]) -> "And":
|
|
91
|
+
return cls(
|
|
92
|
+
Expression.from_dict(data[ExpressionKey.LEFT]),
|
|
93
|
+
Expression.from_dict(data[ExpressionKey.RIGHT]),
|
|
94
|
+
)
|
|
95
|
+
|
|
44
96
|
|
|
45
97
|
class Or(Expression):
|
|
46
98
|
def __init__(self, left: Expression, right: Expression) -> None:
|
|
@@ -56,6 +108,20 @@ class Or(Expression):
|
|
|
56
108
|
def to_sqlalchemy(self, context: Any) -> Any:
|
|
57
109
|
return self.left.to_sqlalchemy(context) | self.right.to_sqlalchemy(context)
|
|
58
110
|
|
|
111
|
+
def to_dict(self) -> dict[str, Any]:
|
|
112
|
+
return {
|
|
113
|
+
ExpressionKey.TYPE: ExpressionType.OR,
|
|
114
|
+
ExpressionKey.LEFT: self.left.to_dict(),
|
|
115
|
+
ExpressionKey.RIGHT: self.right.to_dict(),
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
@classmethod
|
|
119
|
+
def from_dict(cls, data: dict[str, Any]) -> "Or":
|
|
120
|
+
return cls(
|
|
121
|
+
Expression.from_dict(data[ExpressionKey.LEFT]),
|
|
122
|
+
Expression.from_dict(data[ExpressionKey.RIGHT]),
|
|
123
|
+
)
|
|
124
|
+
|
|
59
125
|
|
|
60
126
|
class Not(Expression):
|
|
61
127
|
def __init__(self, expr: Expression) -> None:
|
|
@@ -69,3 +135,13 @@ class Not(Expression):
|
|
|
69
135
|
|
|
70
136
|
def to_sqlalchemy(self, context: Any) -> Any:
|
|
71
137
|
return ~self.expr.to_sqlalchemy(context)
|
|
138
|
+
|
|
139
|
+
def to_dict(self) -> dict[str, Any]:
|
|
140
|
+
return {
|
|
141
|
+
ExpressionKey.TYPE: ExpressionType.NOT,
|
|
142
|
+
ExpressionKey.EXPR: self.expr.to_dict(),
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
@classmethod
|
|
146
|
+
def from_dict(cls, data: dict[str, Any]) -> "Not":
|
|
147
|
+
return cls(Expression.from_dict(data[ExpressionKey.EXPR]))
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Stable serialization tags and dict keys for expression trees.
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from corekit.schemas.enum import StringEnum
|
|
6
|
+
|
|
7
|
+
__all__ = ["ExpressionKey", "ExpressionType"]
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
class ExpressionType(StringEnum):
|
|
11
|
+
"""
|
|
12
|
+
Node kind for non-comparison expression nodes.
|
|
13
|
+
|
|
14
|
+
Comparison nodes use ``Operator.serialized`` (from ``Dialect.name``) instead.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
AND = "and"
|
|
18
|
+
OR = "or"
|
|
19
|
+
NOT = "not"
|
|
20
|
+
FIELD = "field"
|
|
21
|
+
LITERAL = "literal"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class ExpressionKey(StringEnum):
|
|
25
|
+
"""
|
|
26
|
+
Dict keys used by ``Expression.to_dict`` / ``from_dict``.
|
|
27
|
+
"""
|
|
28
|
+
|
|
29
|
+
TYPE = "type"
|
|
30
|
+
LEFT = "left"
|
|
31
|
+
RIGHT = "right"
|
|
32
|
+
EXPR = "expr"
|
|
33
|
+
NAME = "name"
|
|
34
|
+
VALUE = "value"
|
|
@@ -11,13 +11,15 @@ __all__ = ["Dialect", "Operator"]
|
|
|
11
11
|
|
|
12
12
|
class Dialect(NamedTuple):
|
|
13
13
|
"""
|
|
14
|
-
How one operator is spelled for humans.
|
|
14
|
+
How one operator is spelled for humans and for JSON.
|
|
15
15
|
|
|
16
|
-
|
|
17
|
-
|
|
16
|
+
``symbol`` is the infix form (``>=``). ``name`` is the stable serialization
|
|
17
|
+
key (``greater_than_or_equals``). SQL is compiled through SQLAlchemy, not
|
|
18
|
+
spelled here.
|
|
18
19
|
"""
|
|
19
20
|
|
|
20
21
|
symbol: str
|
|
22
|
+
name: str
|
|
21
23
|
|
|
22
24
|
|
|
23
25
|
class Operator(ValidatingEnum):
|
|
@@ -25,16 +27,35 @@ class Operator(ValidatingEnum):
|
|
|
25
27
|
A comparison operator, identified by the comparison class that uses it.
|
|
26
28
|
"""
|
|
27
29
|
|
|
28
|
-
EQUALS = Dialect("==")
|
|
29
|
-
NOT_EQUALS = Dialect("!=")
|
|
30
|
-
LESS_THAN = Dialect("<")
|
|
31
|
-
LESS_THAN_OR_EQUALS = Dialect("<=")
|
|
32
|
-
GREATER_THAN = Dialect(">")
|
|
33
|
-
GREATER_THAN_OR_EQUALS = Dialect(">=")
|
|
34
|
-
IS_IN = Dialect("is in")
|
|
35
|
-
CONTAINS = Dialect("contains")
|
|
36
|
-
ICONTAINS = Dialect("icontains")
|
|
30
|
+
EQUALS = Dialect("==", "equals")
|
|
31
|
+
NOT_EQUALS = Dialect("!=", "not_equals")
|
|
32
|
+
LESS_THAN = Dialect("<", "less_than")
|
|
33
|
+
LESS_THAN_OR_EQUALS = Dialect("<=", "less_than_or_equals")
|
|
34
|
+
GREATER_THAN = Dialect(">", "greater_than")
|
|
35
|
+
GREATER_THAN_OR_EQUALS = Dialect(">=", "greater_than_or_equals")
|
|
36
|
+
IS_IN = Dialect("is in", "is_in")
|
|
37
|
+
CONTAINS = Dialect("contains", "contains")
|
|
38
|
+
ICONTAINS = Dialect("icontains", "icontains")
|
|
37
39
|
|
|
38
40
|
@property
|
|
39
41
|
def symbol(self) -> str:
|
|
40
42
|
return self.value.symbol
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def serialized(self) -> str:
|
|
46
|
+
"""
|
|
47
|
+
Stable type tag for ``to_dict`` / ``from_dict`` (``Dialect.name``).
|
|
48
|
+
|
|
49
|
+
Named ``serialized`` so it does not shadow ``Enum.name``.
|
|
50
|
+
"""
|
|
51
|
+
return self.value.name
|
|
52
|
+
|
|
53
|
+
@classmethod
|
|
54
|
+
def from_serialized(cls, name: str) -> "Operator":
|
|
55
|
+
"""
|
|
56
|
+
Resolve an operator from its ``Dialect.name`` / ``serialized`` tag.
|
|
57
|
+
"""
|
|
58
|
+
for member in cls:
|
|
59
|
+
if member.serialized == name:
|
|
60
|
+
return member
|
|
61
|
+
raise ValueError(f"Unknown operator serialization {name!r}")
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: python-corekit
|
|
3
|
-
Version: 0.6.
|
|
3
|
+
Version: 0.6.4
|
|
4
4
|
Summary: Shared foundations for Python projects: logging, benchmarking, registries, FastAPI application and routers, SQL statements and migrations, background tasks, ETL, LLM chat/tool primitives, and HTML scraping
|
|
5
5
|
Author: Steven Jacobsen
|
|
6
6
|
License-Expression: MIT
|
|
@@ -39,14 +39,19 @@ corekit/crypto/__init__.py,sha256=Qf_FCUoG_jb7Q9tnN4ctX8I6xyaeaJwk74ag_bSchAQ,87
|
|
|
39
39
|
corekit/crypto/constants.py,sha256=m-uq7_EJ4XfUTSZxFv6h429UkKSrGTj3o_9DfRFGyvU,298
|
|
40
40
|
corekit/crypto/enum.py,sha256=0csj06cATCYDPY_QTNy66j_hB16WCqcHg8tJOO0lMNU,212
|
|
41
41
|
corekit/crypto/hasher.py,sha256=KkxBM8pwaFwdUV31D-LO7Pg8bFULI5Y8rtUDTWti08w,3184
|
|
42
|
-
corekit/data/__init__.py,sha256=
|
|
42
|
+
corekit/data/__init__.py,sha256=sb2cbaZ8QM6NsywCtkckrRqwpjpEp33L_R0sTUN26xY,2135
|
|
43
43
|
corekit/data/dataset.py,sha256=TK1yAs7bNCQpV7Z16YqCzYf2Q_Vpu2IbEs1sqMMbikM,12835
|
|
44
44
|
corekit/data/record.py,sha256=EczoOvcxl-lHO1M92AjUh_5E9UQJ2qwBsiu6Yo-34gs,5233
|
|
45
45
|
corekit/data/stats.py,sha256=cRnLGgUHEz66GS1Rs7c_wr2ZVvIJ8WbKq4ifBKR_t0U,4950
|
|
46
|
-
corekit/data/
|
|
47
|
-
corekit/data/
|
|
48
|
-
corekit/data/
|
|
49
|
-
corekit/data/
|
|
46
|
+
corekit/data/arithmetic/__init__.py,sha256=i7MA1FtUdCk6fUqh5qgZUaBPANOICCUjiruDJ5NgflU,2337
|
|
47
|
+
corekit/data/arithmetic/expression.py,sha256=38iLXKrx53pwkwOpE7opt5dCAhDhMMeQCL1Tjwx1bnA,13164
|
|
48
|
+
corekit/data/arithmetic/keys.py,sha256=0G4wGbCsdiod-4T6W8cR6FxnAUv_hHJlaq6s0Rp_L1k,758
|
|
49
|
+
corekit/data/arithmetic/operator.py,sha256=MYL3GvUYJK4jQ0UG0qFDa5N1mLKIA-KuqZleym7_ymk,1225
|
|
50
|
+
corekit/data/expressions/__init__.py,sha256=Vev-d951c7G2oGsUDDynA9SEsFAzgouCy0Py5d3nuwE,2562
|
|
51
|
+
corekit/data/expressions/comparison.py,sha256=eyunBVW96cOpCvHNLgWkQON9-2UcV_-F8ne3mu5ENj0,13678
|
|
52
|
+
corekit/data/expressions/expression.py,sha256=lqPZoYPGalROMMP4Q8uJh3AN7HnSWB0sfwpLWLGIhhU,4702
|
|
53
|
+
corekit/data/expressions/keys.py,sha256=P6wCUbUqrqCbgJMQkpWg8fwM9ZtIgBjByyXLa9UegTo,665
|
|
54
|
+
corekit/data/expressions/operator.py,sha256=lq7MIqa4FtAQZ5FGYF2cVkz_DTG-LiOK0KHu62Y7PNw,1703
|
|
50
55
|
corekit/data/expressions/target.py,sha256=QSl7sH1qFVUc-mL7gsasTsCahWKhHqdo0bMHt--t2m8,470
|
|
51
56
|
corekit/decorators/__init__.py,sha256=YrBcc_4wkSs7nEb3OjC7C7a8fNEvBk3RzOpD8QccHKM,83
|
|
52
57
|
corekit/decorators/exception_handling.py,sha256=p86gfvdmsmC7_va042NSoGkWrJrbLLuw0ncE131wLWU,2326
|
|
@@ -191,8 +196,8 @@ corekit/utils/text.py,sha256=0322DdZGuDGEagTyejuda6QT1jbbxNIO6loC-_AGml0,2311
|
|
|
191
196
|
corekit/utils/time.py,sha256=-iPaETXcgDu7J39Kwe938JyZKhPVjl6a572BBqsqcDQ,2215
|
|
192
197
|
corekit/utils/validators.py,sha256=_HVKo3y264KGNaZ-1RyM1x46VPvu7XKcQkrHWDC9uxs,340
|
|
193
198
|
corekit/utils/void.py,sha256=eXDb2QynuguiSgHGJLdgE08MuRnxBdYebRdMD7s1m9o,178
|
|
194
|
-
python_corekit-0.6.
|
|
195
|
-
python_corekit-0.6.
|
|
196
|
-
python_corekit-0.6.
|
|
197
|
-
python_corekit-0.6.
|
|
198
|
-
python_corekit-0.6.
|
|
199
|
+
python_corekit-0.6.4.dist-info/licenses/LICENSE,sha256=357LYxbxAQZ95q5cV-8JK6j-KNgiE6AteRodjEsm-kE,1072
|
|
200
|
+
python_corekit-0.6.4.dist-info/METADATA,sha256=aS9a2SwmmmLxj-SscQo5gI1ZDfCb5rj7JR0J20Ie4dk,15304
|
|
201
|
+
python_corekit-0.6.4.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
202
|
+
python_corekit-0.6.4.dist-info/top_level.txt,sha256=SDK4o8BoaI47E9tPbiNCbbWoc2y6N_wCjwnIEfr-GWI,8
|
|
203
|
+
python_corekit-0.6.4.dist-info/RECORD,,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|