python-corekit 0.6.2__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.
@@ -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`` is the other
12
- implementation of the same predicate. Operators SQL cannot mean the same way
13
- are refused there rather than compiled into a different query.
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
  ]