pyformula 0.1.0__tar.gz → 0.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,18 @@
1
+ Metadata-Version: 2.3
2
+ Name: pyformula
3
+ Version: 0.2.0
4
+ Summary: A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas.
5
+ Author: aaltatan
6
+ Author-email: aaltatan <a.altatan@gmail.com>
7
+ Classifier: Programming Language :: Python :: 3
8
+ Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
9
+ Classifier: Operating System :: OS Independent
10
+ Requires-Dist: pyvocabulary>=0.1.0
11
+ Requires-Python: >=3.12
12
+ Project-URL: Homepage, https://github.com/aaltatan/pyformula
13
+ Project-URL: Issues, https://github.com/aaltatan/pyformula/issues
14
+ Description-Content-Type: text/markdown
15
+
1
16
  # pyformula
2
17
 
3
18
  A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas.
@@ -852,6 +867,20 @@ The library raises explicit exceptions for common configuration mistakes:
852
867
  - `InvalidExpressionError`: the expression shape is malformed or unsupported
853
868
  - `FormulaAlreadyRegisteredError`: duplicate variable registration name
854
869
  - `FormulaNotRegisteredError`: name is registered but hidden or unavailable
870
+ - `InvalidFormulaNameError`: a variable name is not a Python identifier (`net-salary`)
871
+
872
+ Hidden variables (`hidden=True`) are left out of `registry.variables`, so a
873
+ `FormulaCompiler(registry.variables)` cannot reach them; the decorated function
874
+ still works from Python.
875
+
876
+ Compiler errors inside a nested expression carry a note with the JSON path of the
877
+ part that failed, while their type and message stay the same:
878
+
879
+ ```python
880
+ compiler.compile({"operator": "add", "expressions": ["price", {"sqrt": "taxx"}]})
881
+ # FormulaNotFoundError: Formula not found: taxx. Available formulas: price
882
+ # at $.expressions[1].sqrt
883
+ ```
855
884
 
856
885
  Examples:
857
886
 
@@ -1,17 +1,3 @@
1
- Metadata-Version: 2.3
2
- Name: pyformula
3
- Version: 0.1.0
4
- Summary: A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas.
5
- Author: aaltatan
6
- Author-email: aaltatan <a.altatan@gmail.com>
7
- Classifier: Programming Language :: Python :: 3
8
- Classifier: License :: OSI Approved :: GNU General Public License v3 (GPLv3)
9
- Classifier: Operating System :: OS Independent
10
- Requires-Python: >=3.12
11
- Project-URL: Homepage, https://github.com/aaltatan/pyformula
12
- Project-URL: Issues, https://github.com/aaltatan/pyformula/issues
13
- Description-Content-Type: text/markdown
14
-
15
1
  # pyformula
16
2
 
17
3
  A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas.
@@ -866,6 +852,20 @@ The library raises explicit exceptions for common configuration mistakes:
866
852
  - `InvalidExpressionError`: the expression shape is malformed or unsupported
867
853
  - `FormulaAlreadyRegisteredError`: duplicate variable registration name
868
854
  - `FormulaNotRegisteredError`: name is registered but hidden or unavailable
855
+ - `InvalidFormulaNameError`: a variable name is not a Python identifier (`net-salary`)
856
+
857
+ Hidden variables (`hidden=True`) are left out of `registry.variables`, so a
858
+ `FormulaCompiler(registry.variables)` cannot reach them; the decorated function
859
+ still works from Python.
860
+
861
+ Compiler errors inside a nested expression carry a note with the JSON path of the
862
+ part that failed, while their type and message stay the same:
863
+
864
+ ```python
865
+ compiler.compile({"operator": "add", "expressions": ["price", {"sqrt": "taxx"}]})
866
+ # FormulaNotFoundError: Formula not found: taxx. Available formulas: price
867
+ # at $.expressions[1].sqrt
868
+ ```
869
869
 
870
870
  Examples:
871
871
 
@@ -1,10 +1,10 @@
1
1
  [project]
2
2
  name = "pyformula"
3
- version = "0.1.0"
3
+ version = "0.2.0"
4
4
  description = "A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas."
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
7
- dependencies = []
7
+ dependencies = ["pyvocabulary>=0.1.0"]
8
8
  classifiers = [
9
9
  "Programming Language :: Python :: 3",
10
10
  "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
@@ -1,34 +1,37 @@
1
- [project]
2
- name = "pyformula"
3
- version = "0.1.0"
4
- description = "A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas."
5
- readme = "README.md"
6
- authors = [{ name = "aaltatan", email = "a.altatan@gmail.com" }]
7
- requires-python = ">=3.12"
8
- dependencies = []
9
- classifiers = [
10
- "Programming Language :: Python :: 3",
11
- "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
12
- "Operating System :: OS Independent",
13
- ]
14
-
15
- [project.scripts]
16
- pyformula = "pyformula:main"
17
-
18
- [project.urls]
19
- "Homepage" = "https://github.com/aaltatan/pyformula"
20
- "Issues" = "https://github.com/aaltatan/pyformula/issues"
21
-
22
-
23
- [build-system]
24
- requires = ["uv_build>=0.12.6,<0.13.0"]
25
- build-backend = "uv_build"
26
-
27
- [dependency-groups]
28
- dev = [
29
- "devtools>=0.12.2",
30
- "latexify-py>=0.4.4",
31
- "pyspecification>=2.0.1",
32
- "pytest>=9.1.1",
33
- "pytest-coverage>=0.0",
34
- ]
1
+ [project]
2
+ name = "pyformula"
3
+ version = "0.2.0"
4
+ description = "A lightweight, typed Python library for composing business rules as reusable, executable numeric formulas."
5
+ readme = "README.md"
6
+ authors = [{ name = "aaltatan", email = "a.altatan@gmail.com" }]
7
+ requires-python = ">=3.12"
8
+ dependencies = [
9
+ "pyvocabulary>=0.1.0",
10
+ ]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "License :: OSI Approved :: GNU General Public License v3 (GPLv3)",
14
+ "Operating System :: OS Independent",
15
+ ]
16
+
17
+ [project.scripts]
18
+ pyformula = "pyformula:main"
19
+
20
+ [project.urls]
21
+ "Homepage" = "https://github.com/aaltatan/pyformula"
22
+ "Issues" = "https://github.com/aaltatan/pyformula/issues"
23
+
24
+
25
+
26
+ [build-system]
27
+ requires = ["uv_build>=0.12.6,<0.13.0"]
28
+ build-backend = "uv_build"
29
+
30
+ [dependency-groups]
31
+ dev = [
32
+ "devtools>=0.12.2",
33
+ "latexify-py>=0.4.4",
34
+ "pyspecification>=2.0.1",
35
+ "pytest>=9.1.1",
36
+ "pytest-coverage>=0.0",
37
+ ]
@@ -1,9 +1,12 @@
1
- from .compiler.compiler import FormulaCompiler
1
+ from .compiler.compiler import FormulaCompiler, LiteralFn, decimal_literal
2
2
  from .compiler.models import Expression
3
3
  from .exceptions import (
4
4
  FormulaAlreadyRegisteredError,
5
5
  FormulaNotFoundError,
6
6
  FormulaNotRegisteredError,
7
+ InvalidExpressionError,
8
+ InvalidFormulaNameError,
9
+ PyformulaError,
7
10
  )
8
11
  from .formula import Formula
9
12
  from .models import Number, Operator
@@ -18,9 +21,14 @@ __all__ = [
18
21
  "FormulaCompiler",
19
22
  "FormulaNotFoundError",
20
23
  "FormulaNotRegisteredError",
24
+ "InvalidExpressionError",
25
+ "InvalidFormulaNameError",
26
+ "LiteralFn",
21
27
  "Number",
22
28
  "Operator",
23
29
  "OperatorFn",
30
+ "PyformulaError",
24
31
  "VariablesRegistry",
32
+ "decimal_literal",
25
33
  "variable",
26
34
  ]
@@ -0,0 +1,248 @@
1
+ from collections.abc import Callable, Mapping
2
+ from decimal import Decimal
3
+ from typing import Any, cast
4
+
5
+ from pyvocabulary import index_path, key_path, located
6
+
7
+ from pyformula import math
8
+ from pyformula.exceptions import FormulaNotFoundError, InvalidExpressionError, PyformulaError
9
+ from pyformula.formula import Formula
10
+ from pyformula.models import Number
11
+ from pyformula.operator import OPERATORS
12
+
13
+ from .models import (
14
+ Expression,
15
+ FormulaDict,
16
+ RoundWrapperDict,
17
+ is_formula_dict,
18
+ is_round_wrapper_dict,
19
+ )
20
+
21
+ WRAPPER_FNS: dict[str, Callable[[Formula[Any]], Formula[Any]]] = {
22
+ "positive": lambda fm: +fm,
23
+ "negative": lambda fm: -fm,
24
+ "absolute": abs,
25
+ "ceil": math.ceil,
26
+ "floor": math.floor,
27
+ "trunc": math.trunc,
28
+ "sqrt": math.sqrt,
29
+ "cbrt": math.cbrt,
30
+ "exp": math.exp,
31
+ "exp2": math.exp2,
32
+ "expm1": math.expm1,
33
+ "log10": math.log10,
34
+ "log1p": math.log1p,
35
+ "log2": math.log2,
36
+ "sin": math.sin,
37
+ "sinh": math.sinh,
38
+ "asin": math.asin,
39
+ "asinh": math.asinh,
40
+ "cos": math.cos,
41
+ "cosh": math.cosh,
42
+ "acos": math.acos,
43
+ "acosh": math.acosh,
44
+ "tan": math.tan,
45
+ "tanh": math.tanh,
46
+ "atan": math.atan,
47
+ "atanh": math.atanh,
48
+ "degrees": math.degrees,
49
+ "radians": math.radians,
50
+ "erf": math.erf,
51
+ "erfc": math.erfc,
52
+ "gamma": math.gamma,
53
+ "lgamma": math.lgamma,
54
+ "fabs": math.fabs,
55
+ "ulp": math.ulp,
56
+ }
57
+
58
+
59
+ type LiteralFn = Callable[[Number], Any]
60
+
61
+
62
+ class FormulaCompiler[T]:
63
+ """Compile a structured expression tree into a runtime formula.
64
+
65
+ Args:
66
+ fns: The named formulas an expression may reference.
67
+ literal: Converts every number literal in an expression before use.
68
+ JSON numbers arrive as `float`, so formulas over `Decimal` money
69
+ should pass `literal=decimal_literal`, which goes through `str`
70
+ to keep `0.8` exact. Defaults to using literals as they are.
71
+
72
+ Example:
73
+ ```python
74
+ >>> from decimal import Decimal
75
+ >>> price = Formula(lambda order: order["price"], name="price")
76
+ >>> exact = FormulaCompiler({"price": price}, literal=decimal_literal)
77
+ >>> discounted = exact.compile({"operator": "multiply", "expressions": ["price", 0.8]})
78
+ >>> discounted
79
+ Formula((price * 0.8))
80
+ >>> discounted({"price": Decimal("120.00")})
81
+ Decimal('96.000')
82
+ >>> FormulaCompiler({"price": price}).compile("pricee")
83
+ Traceback (most recent call last):
84
+ ...
85
+ pyformula.exceptions.FormulaNotFoundError: Formula not found: pricee. Available formulas: price
86
+
87
+ ```
88
+
89
+ Examples:
90
+ ```python
91
+ from dataclasses import dataclass
92
+ from pyformula import Formula
93
+
94
+
95
+ @dataclass
96
+ class Rectangular:
97
+ width: float
98
+ height: float
99
+
100
+
101
+ def main() -> None:
102
+ fms: dict[str, Formula[Rectangular]] = {
103
+ "width": Formula[Rectangular](lambda rectangle: rectangle.width),
104
+ "height": Formula[Rectangular](lambda rectangle: rectangle.height),
105
+ }
106
+
107
+ compiler = FormulaCompiler[Rectangular](fms)
108
+
109
+ perimeter = compiler.compile(
110
+ {
111
+ "operator": "multiply",
112
+ "expressions":[
113
+ "operator": "add",
114
+ "expressions": [
115
+ "width",
116
+ "height",
117
+ ], 2,
118
+ ]
119
+ }
120
+ )
121
+
122
+ area = compiler.compile(
123
+ {
124
+ "operator": "multiply",
125
+ "expressions": [
126
+ "width",
127
+ "height",
128
+ ],
129
+ }
130
+ )
131
+
132
+ print(perimeter(Rectangular(width=10, height=20))) # 60.0
133
+ print(area(Rectangular(width=10, height=20))) # 200.0
134
+
135
+ print(perimeter(Rectangular(width=5, height=10))) # 30.0
136
+ print(area(Rectangular(width=5, height=10))) # 50.0
137
+
138
+
139
+ if __name__ == "__main__":
140
+ main()
141
+ ```
142
+
143
+
144
+ """
145
+
146
+ def __init__(
147
+ self,
148
+ fns: Mapping[str, Formula[T]],
149
+ /,
150
+ *,
151
+ literal: LiteralFn | None = None,
152
+ ) -> None:
153
+ self._fns = fns
154
+ self._literal = literal
155
+
156
+ def compile(self, expression: Expression) -> Formula[T]:
157
+ """Compile an expression object into a formula callable for a given model type."""
158
+ if isinstance(expression, bool):
159
+ raise InvalidExpressionError(expression)
160
+
161
+ if isinstance(expression, (int, float, Decimal)):
162
+ return self._compile_literal(expression)
163
+
164
+ if isinstance(expression, str):
165
+ return self._compile_name(expression)
166
+
167
+ if is_formula_dict(expression):
168
+ return self._compile_formula(expression)
169
+
170
+ if is_round_wrapper_dict(expression):
171
+ return self._compile_round(expression)
172
+
173
+ if isinstance(expression, dict):
174
+ wrapped = self._compile_wrapper(expression)
175
+ if wrapped is not None:
176
+ return wrapped
177
+
178
+ raise InvalidExpressionError(expression)
179
+
180
+ def _compile_literal(self, number: Number) -> Formula[T]:
181
+ value = number if self._literal is None else self._literal(number)
182
+ return Formula(lambda _: value, name=str(value))
183
+
184
+ def _compile_name(self, name: str) -> Formula[T]:
185
+ if name not in self._fns:
186
+ raise FormulaNotFoundError(name, self._fns.keys())
187
+
188
+ return self._fns[name]
189
+
190
+ def _compile_round(self, expression: RoundWrapperDict) -> Formula[T]:
191
+ ndigits = expression["ndigits"]
192
+
193
+ if not isinstance(ndigits, int) or isinstance(ndigits, bool):
194
+ raise InvalidExpressionError(expression)
195
+
196
+ return round(self._compile_at(expression["round"], "$.round"), ndigits=ndigits)
197
+
198
+ def _compile_wrapper(self, expression: Mapping[str, object]) -> Formula[T] | None:
199
+ if len(expression) != 1:
200
+ return None
201
+
202
+ for fn_name, wrap in WRAPPER_FNS.items():
203
+ if fn_name in expression:
204
+ operand = cast("Expression", expression[fn_name])
205
+ return wrap(self._compile_at(operand, key_path("$", fn_name)))
206
+
207
+ return None
208
+
209
+ def _compile_formula(self, fm_dict: FormulaDict) -> Formula[T]:
210
+ expressions = fm_dict["expressions"]
211
+ operator = fm_dict["operator"]
212
+
213
+ if (
214
+ not isinstance(expressions, list)
215
+ or not expressions
216
+ or not isinstance(operator, str)
217
+ or operator not in OPERATORS
218
+ ):
219
+ raise InvalidExpressionError(fm_dict)
220
+
221
+ formula = self._compile_at(expressions[0], "$.expressions[0]")
222
+ applier, _ = OPERATORS[operator]
223
+
224
+ for index, expression in enumerate(expressions[1:], start=1):
225
+ operand = self._compile_at(expression, index_path("$.expressions", index))
226
+ formula = cast("Formula[T]", applier(formula, operand))
227
+
228
+ return formula
229
+
230
+ def _compile_at(self, expression: Expression, path: str) -> Formula[T]:
231
+ # Each level notes its path relative to `$`; `located` prefixes the outer
232
+ # levels, so the error ends up with the absolute path.
233
+ with located(path, PyformulaError):
234
+ return self.compile(expression)
235
+
236
+
237
+ def decimal_literal(number: Number, /) -> Decimal:
238
+ """Convert a JSON number to `Decimal` through `str`, so `0.8` stays exactly `0.8`.
239
+
240
+ Example:
241
+ ```python
242
+ >>> decimal_literal(0.8), Decimal(0.8) == decimal_literal(0.8)
243
+ (Decimal('0.8'), False)
244
+
245
+ ```
246
+
247
+ """
248
+ return number if isinstance(number, Decimal) else Decimal(str(number))
@@ -0,0 +1,68 @@
1
+ """Exceptions raised by pyformula.
2
+
3
+ Every exception derives from `PyformulaError`, so callers can catch the whole
4
+ family at once.
5
+ """
6
+
7
+ from collections.abc import Iterable
8
+ from typing import Any
9
+
10
+
11
+ class PyformulaError(Exception):
12
+ """Base class for every exception raised by pyformula."""
13
+
14
+
15
+ class FormulaAlreadyRegisteredError(PyformulaError):
16
+ """Raised when attempting to register a formula name that already exists."""
17
+
18
+ def __init__(self, name: str) -> None:
19
+ super().__init__(f"Formula already registered: {name}")
20
+
21
+
22
+ class FormulaNotRegisteredError(PyformulaError):
23
+ """Raised when a requested formula name has not been registered."""
24
+
25
+ def __init__(self, name: str) -> None:
26
+ super().__init__(f"Formula not registered: {name}")
27
+
28
+
29
+ class FormulaNotFoundError(PyformulaError):
30
+ """Raised when a compiled expression references a formula that is not in scope.
31
+
32
+ Example:
33
+ ```python
34
+ >>> str(FormulaNotFoundError("pricee", ["price", "quantity"]))
35
+ 'Formula not found: pricee. Available formulas: price, quantity'
36
+
37
+ ```
38
+
39
+ """
40
+
41
+ def __init__(self, name: str, available: Iterable[str] | None = None) -> None:
42
+ msg = f"Formula not found: {name}"
43
+
44
+ if available is not None:
45
+ msg += f". Available formulas: {', '.join(available) or '(none)'}"
46
+
47
+ super().__init__(msg)
48
+
49
+
50
+ class InvalidFormulaNameError(PyformulaError, ValueError):
51
+ """Raised when a formula name is not an ASCII Python identifier.
52
+
53
+ Names end up in JSON expressions, so `net-salary` or a trailing newline is rejected.
54
+ """
55
+
56
+ def __init__(self, name: object, /) -> None:
57
+ super().__init__(
58
+ f"Invalid formula name: {name!r}, "
59
+ "name must start with a letter or underscore "
60
+ "and can only contain letters, numbers and underscores"
61
+ )
62
+
63
+
64
+ class InvalidExpressionError(PyformulaError):
65
+ """Raised when an expression structure does not match the compiler schema."""
66
+
67
+ def __init__(self, expression: Any, /) -> None:
68
+ super().__init__(f"Invalid expression: {expression}")
@@ -1,181 +1,182 @@
1
- import decimal
2
- from collections.abc import Callable
3
- from typing import cast
4
-
5
- from .models import Number, Operator
6
- from .operator import OPERATORS
7
-
8
-
9
- class Formula[T]:
10
- """Represent a lazily evaluated numeric transformation over an input object.
11
-
12
- Formula instances can be composed with arithmetic operators, wrapped with
13
- mathematical functions, and later evaluated by calling the formula with an
14
- instance of the source type.
15
-
16
- # Examples:
17
- ```python
18
- from dataclasses import dataclass
19
- from pyformula import Formula
20
-
21
-
22
- @dataclass
23
- class Rectangular:
24
- width: float
25
- height: float
26
-
27
-
28
- def main() -> None:
29
- width = Formula[Rectangular](lambda rectangle: rectangle.width)
30
- height = Formula[Rectangular](lambda rectangle: rectangle.height)
31
-
32
- perimeter = (width + height) * 2
33
- area = width * height
34
-
35
- r1 = Rectangular(width=10, height=20)
36
- print(perimeter(r1)) # 60.0
37
- print(area(r1)) # 200.0
38
-
39
- r2 = Rectangular(width=5, height=10)
40
- print(perimeter(r2)) # 30.0
41
- print(area(r2)) # 50.0
42
-
43
-
44
- if __name__ == "__main__":
45
- main()
46
- ```
47
- """
48
-
49
- def __init__(
50
- self,
51
- fn: Callable[[T], Number],
52
- *,
53
- name: str | None = None,
54
- ) -> None:
55
- """Create a formula from a callable that derives a numeric value."""
56
- self._fn = fn
57
- self._name = name
58
-
59
- def __call__(self, obj: T) -> Number:
60
- """Evaluate the formula against the provided object."""
61
- return self._fn(obj)
62
-
63
- def __add__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
64
- """Return the sum of this formula and another value or formula."""
65
- return self._operate("add", other, reverse=False)
66
-
67
- def __radd__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
68
- """Return the sum of another value and this formula."""
69
- return self._operate("add", other, reverse=True)
70
-
71
- def __sub__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
72
- """Return this formula minus another value or formula."""
73
- return self._operate("subtract", other, reverse=False)
74
-
75
- def __rsub__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
76
- """Return another value minus this formula."""
77
- return self._operate("subtract", other, reverse=True)
78
-
79
- def __mul__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
80
- """Return the product of this formula and another value or formula."""
81
- return self._operate("multiply", other, reverse=False)
82
-
83
- def __rmul__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
84
- """Return another value multiplied by this formula."""
85
- return self._operate("multiply", other, reverse=True)
86
-
87
- def __truediv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
88
- """Return this formula divided by another value or formula."""
89
- return self._operate("divide", other, reverse=False)
90
-
91
- def __rtruediv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
92
- """Return another value divided by this formula."""
93
- return self._operate("divide", other, reverse=True)
94
-
95
- def __mod__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
96
- """Return the modulo of this formula with another value or formula."""
97
- return self._operate("modulo", other, reverse=False)
98
-
99
- def __rmod__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
100
- """Return the modulo of another value with this formula."""
101
- return self._operate("modulo", other, reverse=True)
102
-
103
- def __floordiv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
104
- """Return the floor division of this formula and another value or formula."""
105
- return self._operate("floor_divide", other, reverse=False)
106
-
107
- def __rfloordiv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
108
- """Return the floor division of another value by this formula."""
109
- return self._operate("floor_divide", other, reverse=True)
110
-
111
- def __pow__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
112
- """Return this formula raised to the power of another value or formula."""
113
- return self._operate("power", other, reverse=False)
114
-
115
- def __rpow__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
116
- """Return another value raised to the power of this formula."""
117
- return self._operate("power", other, reverse=True)
118
-
119
- def __pos__(self) -> "Formula[T]":
120
- """Return a formula that preserves the value of the current formula."""
121
- return Formula(self, name=f"+{self}")
122
-
123
- def __neg__(self) -> "Formula[T]":
124
- """Return a formula that negates the current formula's value."""
125
- return Formula(lambda obj: -self(obj), name=f"-{self}")
126
-
127
- def __abs__(self) -> "Formula[T]":
128
- """Return a formula that computes the absolute value of this formula."""
129
- return Formula(lambda obj: abs(self(obj)), name=f"|{self}|")
130
-
131
- def __round__(self, ndigits: int | None = None) -> "Formula[T]":
132
- """Return a formula that rounds the current result to the given precision."""
133
-
134
- def inner(obj: T) -> Number:
135
- value = self(obj)
136
-
137
- if isinstance(value, decimal.Decimal):
138
- rounded = round(value, ndigits)
139
- if isinstance(rounded, decimal.Decimal):
140
- return rounded
141
-
142
- return decimal.Decimal.from_float(rounded)
143
-
144
- if isinstance(value, float):
145
- return float(round(value, ndigits))
146
-
147
- return int(round(value, ndigits))
148
-
149
- return Formula(inner, name=f"round({self}, {ndigits})")
150
-
151
- def __str__(self) -> str:
152
- if self._name is not None:
153
- return self._name
154
-
155
- if self._fn.__name__ == "<lambda>":
156
- return "anonymous"
157
-
158
- return self._fn.__name__
159
-
160
- def __repr__(self) -> str:
161
- return f"Formula({self})"
162
-
163
- def _operate(
164
- self,
165
- operator: Operator,
166
- other: "Formula[T] | Number",
167
- *,
168
- reverse: bool,
169
- ) -> "Formula[T]":
170
- operator_fn, symbol = OPERATORS[operator]
171
- other_fn = other if isinstance(other, Formula) else Formula(lambda _: other)
172
-
173
- def inner(obj: T) -> Number:
174
- value = self(obj)
175
- other_value = other_fn(obj)
176
- return cast(
177
- "Number",
178
- (operator_fn(other_value, value)) if reverse else operator_fn(value, other_value),
179
- )
180
-
181
- return Formula(inner, name=f"({self} {symbol} {other})")
1
+ import decimal
2
+ from collections.abc import Callable
3
+ from typing import cast
4
+
5
+ from .models import Number, Operator
6
+ from .operator import OPERATORS
7
+
8
+
9
+ class Formula[T]:
10
+ """Represent a lazily evaluated numeric transformation over an input object.
11
+
12
+ Formula instances can be composed with arithmetic operators, wrapped with
13
+ mathematical functions, and later evaluated by calling the formula with an
14
+ instance of the source type.
15
+
16
+ # Examples:
17
+ ```python
18
+ from dataclasses import dataclass
19
+ from pyformula import Formula
20
+
21
+
22
+ @dataclass
23
+ class Rectangular:
24
+ width: float
25
+ height: float
26
+
27
+
28
+ def main() -> None:
29
+ width = Formula[Rectangular](lambda rectangle: rectangle.width)
30
+ height = Formula[Rectangular](lambda rectangle: rectangle.height)
31
+
32
+ perimeter = (width + height) * 2
33
+ area = width * height
34
+
35
+ r1 = Rectangular(width=10, height=20)
36
+ print(perimeter(r1)) # 60.0
37
+ print(area(r1)) # 200.0
38
+
39
+ r2 = Rectangular(width=5, height=10)
40
+ print(perimeter(r2)) # 30.0
41
+ print(area(r2)) # 50.0
42
+
43
+
44
+ if __name__ == "__main__":
45
+ main()
46
+ ```
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ fn: Callable[[T], Number],
52
+ *,
53
+ name: str | None = None,
54
+ ) -> None:
55
+ """Create a formula from a callable that derives a numeric value."""
56
+ self._fn = fn
57
+ self._name = name
58
+
59
+ def __call__(self, obj: T) -> Number:
60
+ """Evaluate the formula against the provided object."""
61
+ return self._fn(obj)
62
+
63
+ def __add__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
64
+ """Return the sum of this formula and another value or formula."""
65
+ return self._operate("add", other, reverse=False)
66
+
67
+ def __radd__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
68
+ """Return the sum of another value and this formula."""
69
+ return self._operate("add", other, reverse=True)
70
+
71
+ def __sub__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
72
+ """Return this formula minus another value or formula."""
73
+ return self._operate("subtract", other, reverse=False)
74
+
75
+ def __rsub__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
76
+ """Return another value minus this formula."""
77
+ return self._operate("subtract", other, reverse=True)
78
+
79
+ def __mul__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
80
+ """Return the product of this formula and another value or formula."""
81
+ return self._operate("multiply", other, reverse=False)
82
+
83
+ def __rmul__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
84
+ """Return another value multiplied by this formula."""
85
+ return self._operate("multiply", other, reverse=True)
86
+
87
+ def __truediv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
88
+ """Return this formula divided by another value or formula."""
89
+ return self._operate("divide", other, reverse=False)
90
+
91
+ def __rtruediv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
92
+ """Return another value divided by this formula."""
93
+ return self._operate("divide", other, reverse=True)
94
+
95
+ def __mod__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
96
+ """Return the modulo of this formula with another value or formula."""
97
+ return self._operate("modulo", other, reverse=False)
98
+
99
+ def __rmod__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
100
+ """Return the modulo of another value with this formula."""
101
+ return self._operate("modulo", other, reverse=True)
102
+
103
+ def __floordiv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
104
+ """Return the floor division of this formula and another value or formula."""
105
+ return self._operate("floor_divide", other, reverse=False)
106
+
107
+ def __rfloordiv__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
108
+ """Return the floor division of another value by this formula."""
109
+ return self._operate("floor_divide", other, reverse=True)
110
+
111
+ def __pow__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
112
+ """Return this formula raised to the power of another value or formula."""
113
+ return self._operate("power", other, reverse=False)
114
+
115
+ def __rpow__(self, other: "Formula[T] | Number", /) -> "Formula[T]":
116
+ """Return another value raised to the power of this formula."""
117
+ return self._operate("power", other, reverse=True)
118
+
119
+ def __pos__(self) -> "Formula[T]":
120
+ """Return a formula that preserves the value of the current formula."""
121
+ return Formula(self, name=f"+{self}")
122
+
123
+ def __neg__(self) -> "Formula[T]":
124
+ """Return a formula that negates the current formula's value."""
125
+ return Formula(lambda obj: -self(obj), name=f"-{self}")
126
+
127
+ def __abs__(self) -> "Formula[T]":
128
+ """Return a formula that computes the absolute value of this formula."""
129
+ # abs() over the `Number` union infers `object` in mypy
130
+ return Formula(lambda obj: cast("Number", abs(self(obj))), name=f"|{self}|")
131
+
132
+ def __round__(self, ndigits: int | None = None) -> "Formula[T]":
133
+ """Return a formula that rounds the current result to the given precision."""
134
+
135
+ def inner(obj: T) -> Number:
136
+ value = self(obj)
137
+
138
+ if isinstance(value, decimal.Decimal):
139
+ rounded = round(value, ndigits)
140
+ if isinstance(rounded, decimal.Decimal):
141
+ return rounded
142
+
143
+ return decimal.Decimal(rounded)
144
+
145
+ if isinstance(value, float):
146
+ return float(round(value, ndigits))
147
+
148
+ return int(round(value, ndigits))
149
+
150
+ return Formula(inner, name=f"round({self}, {ndigits})")
151
+
152
+ def __str__(self) -> str:
153
+ if self._name is not None:
154
+ return self._name
155
+
156
+ if self._fn.__name__ == "<lambda>":
157
+ return "anonymous"
158
+
159
+ return self._fn.__name__
160
+
161
+ def __repr__(self) -> str:
162
+ return f"Formula({self})"
163
+
164
+ def _operate(
165
+ self,
166
+ operator: Operator,
167
+ other: "Formula[T] | Number",
168
+ *,
169
+ reverse: bool,
170
+ ) -> "Formula[T]":
171
+ operator_fn, symbol = OPERATORS[operator]
172
+ other_fn = other if isinstance(other, Formula) else Formula(lambda _: other)
173
+
174
+ def inner(obj: T) -> Number:
175
+ value = self(obj)
176
+ other_value = other_fn(obj)
177
+ return cast(
178
+ "Number",
179
+ (operator_fn(other_value, value)) if reverse else operator_fn(value, other_value),
180
+ )
181
+
182
+ return Formula(inner, name=f"({self} {symbol} {other})")
@@ -1,52 +1,58 @@
1
- from collections.abc import Callable
2
- from decimal import Decimal
3
- from typing import Any, Protocol, TypeAlias
4
-
5
- from .models import Operator
6
-
7
-
8
- class SupportsMathOperator(Protocol):
9
- def __add__(self, other: Any, /) -> Any: ...
10
- def __radd__(self, other: Any, /) -> Any: ...
11
- def __sub__(self, other: Any, /) -> Any: ...
12
- def __rsub__(self, other: Any, /) -> Any: ...
13
- def __mul__(self, other: Any, /) -> Any: ...
14
- def __rmul__(self, other: Any, /) -> Any: ...
15
- def __truediv__(self, other: Any, /) -> Any: ...
16
- def __rtruediv__(self, other: Any, /) -> Any: ...
17
- def __mod__(self, other: Any, /) -> Any: ...
18
- def __rmod__(self, other: Any, /) -> Any: ...
19
- def __floordiv__(self, other: Any, /) -> Any: ...
20
- def __rfloordiv__(self, other: Any, /) -> Any: ...
21
- def __pow__(self, other: Any, /) -> Any: ...
22
- def __rpow__(self, other: Any, /) -> Any: ...
23
- def __pos__(self) -> Any: ...
24
- def __neg__(self) -> Any: ...
25
- def __abs__(self) -> Any: ...
26
-
27
-
28
- OperatorFn: TypeAlias = Callable[[SupportsMathOperator, SupportsMathOperator], SupportsMathOperator]
29
-
30
-
31
- def _safe_operate(fn: OperatorFn) -> OperatorFn:
32
- def inner(a: SupportsMathOperator, b: SupportsMathOperator) -> SupportsMathOperator:
33
- if isinstance(a, Decimal) and isinstance(b, float):
34
- b = Decimal.from_float(b)
35
-
36
- if isinstance(b, Decimal) and isinstance(a, float):
37
- a = Decimal.from_float(a)
38
-
39
- return fn(a, b)
40
-
41
- return inner
42
-
43
-
44
- OPERATORS: dict[Operator, tuple[OperatorFn, str]] = {
45
- "add": (_safe_operate(lambda a, b: a + b), "+"),
46
- "subtract": (_safe_operate(lambda a, b: a - b), "-"),
47
- "multiply": (_safe_operate(lambda a, b: a * b), "*"),
48
- "divide": (_safe_operate(lambda a, b: a / b), "/"),
49
- "modulo": (_safe_operate(lambda a, b: a % b), "%"),
50
- "floor_divide": (_safe_operate(lambda a, b: a // b), "//"),
51
- "power": (_safe_operate(lambda a, b: a**b), "**"),
52
- }
1
+ from collections.abc import Callable
2
+ from decimal import Decimal
3
+ from typing import Any, Protocol, TypeAlias
4
+
5
+ from .models import Operator
6
+
7
+
8
+ class SupportsMathOperator(Protocol):
9
+ def __add__(self, other: Any, /) -> Any: ...
10
+ def __radd__(self, other: Any, /) -> Any: ...
11
+ def __sub__(self, other: Any, /) -> Any: ...
12
+ def __rsub__(self, other: Any, /) -> Any: ...
13
+ def __mul__(self, other: Any, /) -> Any: ...
14
+ def __rmul__(self, other: Any, /) -> Any: ...
15
+ def __truediv__(self, other: Any, /) -> Any: ...
16
+ def __rtruediv__(self, other: Any, /) -> Any: ...
17
+ def __mod__(self, other: Any, /) -> Any: ...
18
+ def __rmod__(self, other: Any, /) -> Any: ...
19
+ def __floordiv__(self, other: Any, /) -> Any: ...
20
+ def __rfloordiv__(self, other: Any, /) -> Any: ...
21
+ def __pow__(self, other: Any, /) -> Any: ...
22
+ def __rpow__(self, other: Any, /) -> Any: ...
23
+ def __pos__(self) -> Any: ...
24
+ def __neg__(self) -> Any: ...
25
+ def __abs__(self) -> Any: ...
26
+
27
+
28
+ OperatorFn: TypeAlias = Callable[[SupportsMathOperator, SupportsMathOperator], SupportsMathOperator]
29
+
30
+
31
+ def _safe_operate(fn: OperatorFn) -> OperatorFn:
32
+ def inner(a: SupportsMathOperator, b: SupportsMathOperator) -> SupportsMathOperator:
33
+ if isinstance(a, Decimal) and isinstance(b, float):
34
+ b = Decimal(b)
35
+
36
+ if isinstance(b, Decimal) and isinstance(a, float):
37
+ a = Decimal(a)
38
+
39
+ result = fn(a, b)
40
+
41
+ if isinstance(result, complex):
42
+ msg = f"operation on {a!r} and {b!r} produced an unsupported complex result"
43
+ raise TypeError(msg)
44
+
45
+ return result
46
+
47
+ return inner
48
+
49
+
50
+ OPERATORS: dict[Operator, tuple[OperatorFn, str]] = {
51
+ "add": (_safe_operate(lambda a, b: a + b), "+"),
52
+ "subtract": (_safe_operate(lambda a, b: a - b), "-"),
53
+ "multiply": (_safe_operate(lambda a, b: a * b), "*"),
54
+ "divide": (_safe_operate(lambda a, b: a / b), "/"),
55
+ "modulo": (_safe_operate(lambda a, b: a % b), "%"),
56
+ "floor_divide": (_safe_operate(lambda a, b: a // b), "//"),
57
+ "power": (_safe_operate(lambda a, b: a**b), "**"),
58
+ }
@@ -1,6 +1,12 @@
1
- from collections.abc import Callable
1
+ from collections.abc import Callable, Mapping
2
2
 
3
- from .exceptions import FormulaAlreadyRegisteredError, FormulaNotRegisteredError
3
+ from pyvocabulary import Vocabulary
4
+
5
+ from .exceptions import (
6
+ FormulaAlreadyRegisteredError,
7
+ FormulaNotRegisteredError,
8
+ InvalidFormulaNameError,
9
+ )
4
10
  from .formula import Formula
5
11
  from .models import Number
6
12
  from .variable import variable
@@ -55,19 +61,20 @@ class VariablesRegistry[T]:
55
61
 
56
62
  def __init__(self) -> None:
57
63
  """Initialize an empty registry with no visible or hidden variables."""
58
- self._variables: dict[str, Formula[T]] = {}
59
- self._hidden: set[str] = set()
64
+ self._variables: Vocabulary[Formula[T]] = Vocabulary(
65
+ "formula",
66
+ does_not_exist=lambda name, _: FormulaNotRegisteredError(name),
67
+ already_registered=FormulaAlreadyRegisteredError,
68
+ invalid_name=InvalidFormulaNameError,
69
+ )
60
70
 
61
71
  @property
62
- def variables(self) -> dict[str, Formula[T]]:
63
- """Return the mapping of registered variable names to formula instances."""
72
+ def variables(self) -> Mapping[str, Formula[T]]:
73
+ """Return a read-only view of the visible variables, the ones a compiler may use."""
64
74
  return self._variables
65
75
 
66
76
  def __getitem__(self, name: str) -> Formula[T]:
67
77
  """Return a registered variable by name, raising if it is hidden or missing."""
68
- if name in self._hidden or name not in self._variables:
69
- raise FormulaNotRegisteredError(name)
70
-
71
78
  return self._variables[name]
72
79
 
73
80
  def variable(
@@ -106,18 +113,9 @@ class VariablesRegistry[T]:
106
113
  hidden: bool,
107
114
  ) -> Formula[T]:
108
115
  reg_name = name or fn.__name__
109
-
110
- if reg_name in self._variables:
111
- raise FormulaAlreadyRegisteredError(reg_name)
112
-
113
- if hidden:
114
- self._hidden.add(reg_name)
115
-
116
116
  var = variable(name=reg_name)(fn)
117
117
 
118
118
  if description or fn.__doc__:
119
119
  var.__doc__ = description or fn.__doc__
120
120
 
121
- self._variables[reg_name] = var
122
-
123
- return var
121
+ return self._variables.add(reg_name, var, hidden=hidden)
@@ -1,5 +1,5 @@
1
1
  from collections.abc import Callable
2
- from functools import wraps
2
+ from functools import update_wrapper
3
3
 
4
4
  from .formula import Formula
5
5
  from .models import Number
@@ -51,10 +51,8 @@ def variable[T](*, name: str | None = None) -> Callable[[Callable[[T], Number]],
51
51
  """
52
52
 
53
53
  def decorator(fn: Callable[[T], Number]) -> Formula[T]:
54
- @wraps(fn)
55
- def wrapper(fn: Callable[[T], Number]) -> Callable[[T], Number]:
56
- return fn
57
-
58
- return Formula(wrapper(fn), name=name or fn.__name__)
54
+ formula = Formula(fn, name=name or fn.__name__)
55
+ update_wrapper(formula, fn)
56
+ return formula
59
57
 
60
58
  return decorator
@@ -1,160 +0,0 @@
1
- from collections.abc import Callable
2
- from decimal import Decimal
3
- from typing import Any, cast
4
-
5
- from pyformula import math
6
- from pyformula.exceptions import FormulaNotFoundError, InvalidExpressionError
7
- from pyformula.formula import Formula
8
- from pyformula.operator import OPERATORS
9
-
10
- from .models import Expression, FormulaDict, is_formula_dict, is_round_wrapper_dict
11
-
12
- WRAPPER_FNS: dict[str, Callable[[Formula[Any]], Formula[Any]]] = {
13
- "positive": lambda fm: +fm,
14
- "negative": lambda fm: -fm,
15
- "absolute": abs,
16
- "ceil": math.ceil,
17
- "floor": math.floor,
18
- "trunc": math.trunc,
19
- "sqrt": math.sqrt,
20
- "cbrt": math.cbrt,
21
- "exp": math.exp,
22
- "exp2": math.exp2,
23
- "expm1": math.expm1,
24
- "log10": math.log10,
25
- "log1p": math.log1p,
26
- "log2": math.log2,
27
- "sin": math.sin,
28
- "sinh": math.sinh,
29
- "asin": math.asin,
30
- "asinh": math.asinh,
31
- "cos": math.cos,
32
- "cosh": math.cosh,
33
- "acos": math.acos,
34
- "acosh": math.acosh,
35
- "tan": math.tan,
36
- "tanh": math.tanh,
37
- "atan": math.atan,
38
- "atanh": math.atanh,
39
- "degrees": math.degrees,
40
- "radians": math.radians,
41
- "erf": math.erf,
42
- "erfc": math.erfc,
43
- "gamma": math.gamma,
44
- "lgamma": math.lgamma,
45
- "fabs": math.fabs,
46
- "ulp": math.ulp,
47
- }
48
-
49
-
50
- class FormulaCompiler[T]:
51
- """Compile a structured expression tree into a runtime formula.
52
-
53
- Examples:
54
- ```python
55
- from dataclasses import dataclass
56
- from pyformula import Formula
57
-
58
-
59
- @dataclass
60
- class Rectangular:
61
- width: float
62
- height: float
63
-
64
-
65
- def main() -> None:
66
- fms: dict[str, Formula[Rectangular]] = {
67
- "width": Formula[Rectangular](lambda rectangle: rectangle.width),
68
- "height": Formula[Rectangular](lambda rectangle: rectangle.height),
69
- }
70
-
71
- compiler = FormulaCompiler[Rectangular](fms)
72
-
73
- perimeter = compiler.compile(
74
- {
75
- "operator": "multiply",
76
- "expressions":[
77
- "operator": "add",
78
- "expressions": [
79
- "width",
80
- "height",
81
- ], 2,
82
- ]
83
- }
84
- )
85
-
86
- area = compiler.compile(
87
- {
88
- "operator": "multiply",
89
- "expressions": [
90
- "width",
91
- "height",
92
- ],
93
- }
94
- )
95
-
96
- print(perimeter(Rectangular(width=10, height=20))) # 60.0
97
- print(area(Rectangular(width=10, height=20))) # 200.0
98
-
99
- print(perimeter(Rectangular(width=5, height=10))) # 30.0
100
- print(area(Rectangular(width=5, height=10))) # 50.0
101
-
102
-
103
- if __name__ == "__main__":
104
- main()
105
- ```
106
-
107
-
108
- """
109
-
110
- def __init__(self, fns: dict[str, Formula[T]], /) -> None:
111
- self._fns = fns
112
-
113
- def compile(self, expression: Expression) -> Formula[T]:
114
- """Compile an expression object into a formula callable for a given model type."""
115
- if isinstance(expression, (int, float, Decimal)):
116
- return Formula(lambda _: expression)
117
-
118
- if isinstance(expression, str) and expression not in self._fns:
119
- raise FormulaNotFoundError(expression)
120
-
121
- if isinstance(expression, str):
122
- return self._fns[expression]
123
-
124
- if is_formula_dict(expression):
125
- return self._compile_formula(expression)
126
-
127
- if is_round_wrapper_dict(expression) and not isinstance(expression["ndigits"], int):
128
- raise InvalidExpressionError(expression)
129
-
130
- if is_round_wrapper_dict(expression):
131
- return round(self.compile(expression["round"]), ndigits=expression["ndigits"])
132
-
133
- if not isinstance(expression, dict):
134
- raise InvalidExpressionError(expression)
135
-
136
- for fn_name, wrap in WRAPPER_FNS.items():
137
- if fn_name in expression and len(expression) == 1:
138
- return wrap(self.compile(expression[fn_name]))
139
-
140
- raise InvalidExpressionError(expression)
141
-
142
- def _compile_formula(self, fm_dict: FormulaDict) -> Formula[T]:
143
- expressions = fm_dict["expressions"]
144
- operator = fm_dict["operator"]
145
-
146
- if (
147
- not isinstance(expressions, list)
148
- or not expressions
149
- or not isinstance(operator, str)
150
- or operator not in OPERATORS
151
- ):
152
- raise InvalidExpressionError(fm_dict)
153
-
154
- formula = self.compile(expressions[0])
155
- applier, _ = OPERATORS[operator]
156
-
157
- for expression in expressions[1:]:
158
- formula = applier(formula, self.compile(expression))
159
-
160
- return cast("Formula[T]", formula)
@@ -1,29 +0,0 @@
1
- from typing import Any
2
-
3
-
4
- class FormulaAlreadyRegisteredError(Exception):
5
- """Raised when attempting to register a formula name that already exists."""
6
-
7
- def __init__(self, name: str) -> None:
8
- super().__init__(f"Formula already registered: {name}")
9
-
10
-
11
- class FormulaNotRegisteredError(Exception):
12
- """Raised when a requested formula name has not been registered."""
13
-
14
- def __init__(self, name: str) -> None:
15
- super().__init__(f"Formula not registered: {name}")
16
-
17
-
18
- class FormulaNotFoundError(Exception):
19
- """Raised when a compiled expression references a formula that is not in scope."""
20
-
21
- def __init__(self, name: str) -> None:
22
- super().__init__(f"Formula not found: {name}")
23
-
24
-
25
- class InvalidExpressionError(Exception):
26
- """Raised when an expression structure does not match the compiler schema."""
27
-
28
- def __init__(self, expression: Any, /) -> None:
29
- super().__init__(f"Invalid expression: {expression}")