GeezerVison is showing github.com — Add `__replace_expr__` to modify expr in place · mjdhasan/egglog-python@f842cc8
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: docs/changelog.md +1Lines changed: 1 addition & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -4,6 +4,7 @@ _This project uses semantic versioning_ | 4 | 4 |
| 5 | 5 | ## UNRELEASED | 6 | 6 |
| | 7 | +- Allow mutating methods to update their underlying expression via `Expr.__replace_expr__`, and ensure default rewrites return the mutated receiver when using `mutates_self` or `mutates_first_arg`. | 7 | 8 | - BREAKING: Store `PyObject` values as `cloudpickle` bytes instead of live references so duplicates merge by value; `.value` now returns a fresh copy and the sort accepts objects like `None` that previously failed. | 8 | 9 | - Adds `__call__` method to `PyObject` to replace `py_eval_fn` which is now deprecated. | 9 | 10 | - Improve doctest support, teaching expressions about their `__module__`, `__dir__`, and special methods. | |
Collapse file Copy file name to clipboardExpand all lines: docs/reference/python-integration.md +17-4Lines changed: 17 additions & 4 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -438,7 +438,12 @@ assert str(-1.0 + Int.var("x")) == "Float(-1.0) + Float.from_int(Int.var(\"x\")) | 438 | 438 |
| 439 | 439 | ### Mutating arguments | 440 | 440 |
| 441 | | -In order to support Python functions and methods which mutate their arguments, you can pass in the `mutate_first_arg` keyword argument to the `@function` decorator and the `mutates_self` argument to the `@method` decorator. This will cause the first argument to be mutated in place, instead of being copied. | | 441 | +In order to support Python functions and methods which mutate their arguments, use the `mutates_first_arg` keyword argument on `@function` and the `mutates_self` keyword argument on `@method`. The runtime treats the mutated receiver as the return value of the egglog call, so the default rewrite points the call expression at the updated argument. | | 442 | + | | 443 | +Inside the Python implementation you can call `__replace_expr__` on an `Expr` instance to swap out its underlying egglog expression in-place. This keeps any existing Python references in sync while still allowing the e-graph to reason about the mutated value. The same helper works for methods that run immediately with `@method(preserve=True)`. | | 444 | + | | 445 | +Any function which mutates its first argument must return `None`. In egglog, this is translated into a function which | | 446 | +returns the type of its first argument. | 442 | 447 |
| 443 | 448 | ```{code-cell} python | 444 | 449 | from copy import copy | @@ -465,12 +470,20 @@ mutate_egraph = EGraph() | 465 | 470 | mutate_egraph.register(rewrite(incr_i).to(i + Int(1)), x) | 466 | 471 | mutate_egraph.run(10) | 467 | 472 | mutate_egraph.check(eq(x).to(Int(10) + Int(1))) | | 473 | +
| | 474 | +# incr with the rewrite could also be written like this: | | 475 | +@function(mutates_first_arg=True) | | 476 | +def incr_other(x: Int) -> None: | | 477 | + self.__replace_expr__(x + Int(1)) | | 478 | +x = Int(10) | | 479 | +incr_other(x) | | 480 | +mutate_egraph = EGraph() | | 481 | +mutate_egraph.register(x) | | 482 | +mutate_egraph.run(10) | | 483 | +mutate_egraph.check(eq(x).to(Int(10) + Int(1))) | 468 | 484 | mutate_egraph | 469 | 485 | ``` | 470 | 486 |
| 471 | | -Any function which mutates its first argument must return `None`. In egglog, this is translated into a function which | 472 | | -returns the type of its first argument. | 473 | | - | 474 | 487 | Note that dunder methods such as `__setitem__` will automatically be marked as mutating their first argument. | 475 | 488 |
| 476 | 489 | ## Functions as Values | |
Collapse file Copy file name to clipboardExpand all lines: python/egglog/egraph.py +23-2Lines changed: 23 additions & 2 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -352,11 +352,19 @@ class BaseExpr(metaclass=_ExprMetaclass): | 352 | 352 | Either a builtin or a user defined expression type. | 353 | 353 | """ | 354 | 354 |
| | 355 | + # these methods are only provided for type checking | | 356 | + # The real implementations are in the runtime system | | 357 | + | 355 | 358 | def __ne__(self, other: Self) -> Unit: ... # type: ignore[override, empty-body] | 356 | 359 |
| 357 | 360 | # not currently dissalowing other types of equality https://github.com/python/typeshed/issues/8217#issuecomment-3140873292 | 358 | 361 | def __eq__(self, other: Self) -> Fact: ... # type: ignore[override, empty-body] | 359 | 362 |
| | 363 | + def __replace_expr__(self, new_expr: Self) -> None: | | 364 | + """ | | 365 | + Replace the current expression with the new expression in place. | | 366 | + """ | | 367 | + | 360 | 368 |
| 361 | 369 | class BuiltinExpr(BaseExpr, metaclass=_ExprMetaclass): | 362 | 370 | """ | @@ -484,7 +492,7 @@ def _generate_class_decls( # noqa: C901,PLR0912 | 484 | 492 | except Exception as e: | 485 | 493 | raise add_note(f"Error processing {cls_ident}.{method_name}", e) from None | 486 | 494 |
| 487 | | - if not builtin and not isinstance(ref, InitRef) and not mutates: | | 495 | + if not builtin and not isinstance(ref, InitRef): | 488 | 496 | add_default_funcs.append(add_rewrite) | 489 | 497 |
| 490 | 498 | # Add all rewrite methods at the end so that all methods are registered first and can be accessed | @@ -648,7 +656,16 @@ def _fn_decl( | 648 | 656 | ) | 649 | 657 | decls.set_function_decl(ref, decl) | 650 | 658 | return Thunk.fn( | 651 | | - _add_default_rewrite_function, decls, ref, fn, args, ruleset, subsume, return_type, context=f"creating {ref}" | | 659 | + _add_default_rewrite_function, | | 660 | + decls, | | 661 | + ref, | | 662 | + fn, | | 663 | + args, | | 664 | + ruleset, | | 665 | + subsume, | | 666 | + return_type, | | 667 | + mutates_first_arg, | | 668 | + context=f"creating {ref}", | 652 | 669 | ) | 653 | 670 |
| 654 | 671 |
| @@ -747,6 +764,7 @@ def _add_default_rewrite_function( | 747 | 764 | ruleset: Ruleset | None, | 748 | 765 | subsume: bool, | 749 | 766 | res_type: TypeOrVarRef, | | 767 | + mutates_first_arg: bool, | 750 | 768 | ) -> None: | 751 | 769 | args: list[object] = [RuntimeExpr.__from_values__(decls, a) for a in args] | 752 | 770 |
| @@ -756,6 +774,9 @@ def _add_default_rewrite_function( | 756 | 774 | args.insert(0, RuntimeClass(Thunk.value(decls), tp)) | 757 | 775 | with set_current_ruleset(ruleset): | 758 | 776 | res = fn(*args) | | 777 | + if mutates_first_arg: | | 778 | + res = args[0] | | 779 | + # print(res) | 759 | 780 | _add_default_rewrite(decls, ref, res_type, res, ruleset, subsume) | 760 | 781 |
| 761 | 782 |
| |
Collapse file Copy file name to clipboardExpand all lines: python/egglog/runtime.py +11Lines changed: 11 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -622,10 +622,17 @@ def to_py_signature(sig: FunctionSignature, decls: Declarations, optional_args: | 622 | 622 | return Signature(parameters) | 623 | 623 |
| 624 | 624 |
| | 625 | +ON_CREATE_EXPR: None | Callable[[Callable[[], TypedExprDecl]], None] = None | | 626 | + | | 627 | + | 625 | 628 | @dataclass | 626 | 629 | class RuntimeExpr(DelayedDeclerations): | 627 | 630 | __egg_typed_expr_thunk__: Callable[[], TypedExprDecl] | 628 | 631 |
| | 632 | + def __post_init__(self) -> None: | | 633 | + if ON_CREATE_EXPR: | | 634 | + ON_CREATE_EXPR(self.__egg_typed_expr_thunk__) | | 635 | + | 629 | 636 | @classmethod | 630 | 637 | def __from_values__(cls, d: Declarations, e: TypedExprDecl) -> RuntimeExpr: | 631 | 638 | return cls(Thunk.value(d), Thunk.value(e)) | @@ -734,6 +741,10 @@ def __call__( | 734 | 741 | ) -> object: # define it here only for type checking, it will be overriden below | 735 | 742 | ... | 736 | 743 |
| | 744 | + def __replace_expr__(self, new_expr: RuntimeExpr) -> None: | | 745 | + self.__egg_decls_thunk__ = new_expr.__egg_decls_thunk__ | | 746 | + self.__egg_typed_expr_thunk__ = new_expr.__egg_typed_expr_thunk__ | | 747 | + | 737 | 748 |
| 738 | 749 | # Return a sentinel value to differentiate between no method and property that returns None | 739 | 750 | _no_method_sentinel = object() | |
Collapse file Copy file name to clipboardExpand all lines: python/tests/test_high_level.py +33Lines changed: 33 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -1509,3 +1509,36 @@ def raises(_val): | 1509 | 1509 | egraph = EGraph() | 1510 | 1510 | with pytest.raises(ValueError, match=msg): | 1511 | 1511 | egraph.extract(PyObject(raises)(PyObject(None))) | | 1512 | + | | 1513 | + | | 1514 | +def test_mutates_self_rewrite(): | | 1515 | + mutates_ruleset = ruleset() | | 1516 | + | | 1517 | + class MutateMethod(Expr, ruleset=mutates_ruleset): | | 1518 | + def __init__(self) -> None: ... | | 1519 | + def incr(self) -> MutateMethod: ... | | 1520 | + | | 1521 | + @method(mutates_self=True) | | 1522 | + def mutates(self) -> None: | | 1523 | + self.__replace_expr__(self.incr()) | | 1524 | + | | 1525 | + x = MutateMethod() | | 1526 | + x.mutates() | | 1527 | + egraph = EGraph() | | 1528 | + egraph.register(x) | | 1529 | + egraph.run(mutates_ruleset) | | 1530 | + egraph.check(x == MutateMethod().incr()) | | 1531 | + | | 1532 | + | | 1533 | +def test_mutates_self_preserved(): | | 1534 | + class MutatePreserved(Expr): | | 1535 | + def __init__(self) -> None: ... | | 1536 | + def incr(self) -> MutatePreserved: ... | | 1537 | + | | 1538 | + @method(preserve=True) | | 1539 | + def mutates(self) -> None: | | 1540 | + self.__replace_expr__(self.incr()) | | 1541 | + | | 1542 | + x = MutatePreserved() | | 1543 | + x.mutates() | | 1544 | + assert x == MutatePreserved().incr() |
|