Skip to content

Commit b0f6d8f

Browse files
committed
Base expressions on dataclasses
1 parent 6e9c0a4 commit b0f6d8f

File tree

4 files changed

+341
-419
lines changed

4 files changed

+341
-419
lines changed

doc/index.rst

+13-13
Original file line numberDiff line numberDiff line change
@@ -18,15 +18,15 @@ symbol, *x* in this case.
1818

1919
>>> x = pmbl.var("x")
2020
>>> x
21-
Variable('x')
21+
Variable(name='x')
2222

2323
Next, let's create an expression using *x*:
2424

2525
.. doctest::
2626

2727
>>> u = (x+1)**5
2828
>>> u
29-
Power(Sum((Variable('x'), 1)), 5)
29+
Power(base=Sum(children=(Variable(name='x'), 1)), exponent=5)
3030
>>> print(u)
3131
(x + 1)**5
3232

@@ -69,20 +69,20 @@ You can also easily define your own objects to use inside an expression:
6969

7070
.. doctest::
7171

72-
>>> from pymbolic.primitives import Expression
73-
>>> class FancyOperator(Expression):
74-
... def __init__(self, operand):
75-
... self.operand = operand
76-
...
77-
... def __getinitargs__(self):
78-
... return (self.operand,)
72+
>>> from pymbolic.primitives import Expression, augment_expression_dataclass
73+
>>> from dataclasses import dataclass
74+
>>>
75+
>>> @augment_expression_dataclass
76+
... @dataclass(frozen=True)
77+
... class FancyOperator(Expression):
78+
... operand: Expression
7979
...
8080
... mapper_method = "map_fancy_operator"
8181
...
8282
>>> u
83-
Power(Sum((Variable('x'), 1)), 5)
83+
Power(base=Sum(children=(Variable(name='x'), 1)), exponent=5)
8484
>>> 17*FancyOperator(u)
85-
Product((17, FancyOperator(Power(Sum((..., 1)), 5))))
85+
Product(children=(17, FancyOperator(operand=Power(base=Sum(children=(..., 1)), exponent=5))))
8686

8787
As a final example, we can now derive from *MyMapper* to multiply all
8888
*FancyOperator* instances by 2.
@@ -93,8 +93,8 @@ As a final example, we can now derive from *MyMapper* to multiply all
9393
... def map_fancy_operator(self, expr):
9494
... return 2*FancyOperator(self.rec(expr.operand))
9595
...
96-
>>> MyMapper2()(FancyOperator(u))
97-
Product((2, FancyOperator(Power(Product((..., 1)), 5))))
96+
>>> MyMapper2()(FancyOperator(operand=u))
97+
Product(children=(2, FancyOperator(operand=Power(base=Product(children=(..., 1)), exponent=5))))
9898

9999
.. automodule:: pymbolic
100100

pymbolic/parser.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
THE SOFTWARE.
2121
"""
2222

23+
import immutables
2324
import pytools.lex
2425
from pytools import memoize_method
2526
from sys import intern
@@ -330,7 +331,8 @@ def parse_postfix(self, pstate, min_precedence, left_exp):
330331
args, kwargs = self.parse_arglist(pstate)
331332

332333
if kwargs:
333-
left_exp = primitives.CallWithKwargs(left_exp, args, kwargs)
334+
left_exp = primitives.CallWithKwargs(
335+
left_exp, args, immutables.Map(kwargs))
334336
else:
335337
left_exp = primitives.Call(left_exp, args)
336338

0 commit comments

Comments
 (0)