GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — Add `__replace_expr__` to modify expr in place · mjdhasan/egglog-python@f842cc8

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs
    • changelog.md
    • reference
      • python-integration.md
  • python
    • egglog
      • egraph.py
      • runtime.py
    • tests
      • test_high_level.py
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/changelog.md‎

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 numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ _This project uses semantic versioning_
44

55
## UNRELEASED
66

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`.
78
- 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.
89
- Adds `__call__` method to `PyObject` to replace `py_eval_fn` which is now deprecated.
910
- Improve doctest support, teaching expressions about their `__module__`, `__dir__`, and special methods.
Collapse file

‎docs/reference/python-integration.md‎

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 numberDiff line numberDiff line change
@@ -438,7 +438,12 @@ assert str(-1.0 + Int.var("x")) == "Float(-1.0) + Float.from_int(Int.var(\"x\"))
438438

439439
### Mutating arguments
440440

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.
442447

443448
```{code-cell} python
444449
from copy import copy
@@ -465,12 +470,20 @@ mutate_egraph = EGraph()
465470
mutate_egraph.register(rewrite(incr_i).to(i + Int(1)), x)
466471
mutate_egraph.run(10)
467472
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)))
468484
mutate_egraph
469485
```
470486

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-
474487
Note that dunder methods such as `__setitem__` will automatically be marked as mutating their first argument.
475488

476489
## Functions as Values
Collapse file

‎python/egglog/egraph.py‎

Copy file name to clipboardExpand all lines: python/egglog/egraph.py
+23-2Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -352,11 +352,19 @@ class BaseExpr(metaclass=_ExprMetaclass):
352352
Either a builtin or a user defined expression type.
353353
"""
354354

355+
# these methods are only provided for type checking
356+
# The real implementations are in the runtime system
357+
355358
def __ne__(self, other: Self) -> Unit: ... # type: ignore[override, empty-body]
356359

357360
# not currently dissalowing other types of equality https://github.com/python/typeshed/issues/8217#issuecomment-3140873292
358361
def __eq__(self, other: Self) -> Fact: ... # type: ignore[override, empty-body]
359362

363+
def __replace_expr__(self, new_expr: Self) -> None:
364+
"""
365+
Replace the current expression with the new expression in place.
366+
"""
367+
360368

361369
class BuiltinExpr(BaseExpr, metaclass=_ExprMetaclass):
362370
"""
@@ -484,7 +492,7 @@ def _generate_class_decls( # noqa: C901,PLR0912
484492
except Exception as e:
485493
raise add_note(f"Error processing {cls_ident}.{method_name}", e) from None
486494

487-
if not builtin and not isinstance(ref, InitRef) and not mutates:
495+
if not builtin and not isinstance(ref, InitRef):
488496
add_default_funcs.append(add_rewrite)
489497

490498
# 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(
648656
)
649657
decls.set_function_decl(ref, decl)
650658
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}",
652669
)
653670

654671

@@ -747,6 +764,7 @@ def _add_default_rewrite_function(
747764
ruleset: Ruleset | None,
748765
subsume: bool,
749766
res_type: TypeOrVarRef,
767+
mutates_first_arg: bool,
750768
) -> None:
751769
args: list[object] = [RuntimeExpr.__from_values__(decls, a) for a in args]
752770

@@ -756,6 +774,9 @@ def _add_default_rewrite_function(
756774
args.insert(0, RuntimeClass(Thunk.value(decls), tp))
757775
with set_current_ruleset(ruleset):
758776
res = fn(*args)
777+
if mutates_first_arg:
778+
res = args[0]
779+
# print(res)
759780
_add_default_rewrite(decls, ref, res_type, res, ruleset, subsume)
760781

761782

Collapse file

‎python/egglog/runtime.py‎

Copy file name to clipboardExpand all lines: python/egglog/runtime.py
+11Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -622,10 +622,17 @@ def to_py_signature(sig: FunctionSignature, decls: Declarations, optional_args:
622622
return Signature(parameters)
623623

624624

625+
ON_CREATE_EXPR: None | Callable[[Callable[[], TypedExprDecl]], None] = None
626+
627+
625628
@dataclass
626629
class RuntimeExpr(DelayedDeclerations):
627630
__egg_typed_expr_thunk__: Callable[[], TypedExprDecl]
628631

632+
def __post_init__(self) -> None:
633+
if ON_CREATE_EXPR:
634+
ON_CREATE_EXPR(self.__egg_typed_expr_thunk__)
635+
629636
@classmethod
630637
def __from_values__(cls, d: Declarations, e: TypedExprDecl) -> RuntimeExpr:
631638
return cls(Thunk.value(d), Thunk.value(e))
@@ -734,6 +741,10 @@ def __call__(
734741
) -> object: # define it here only for type checking, it will be overriden below
735742
...
736743

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+
737748

738749
# Return a sentinel value to differentiate between no method and property that returns None
739750
_no_method_sentinel = object()
Collapse file

‎python/tests/test_high_level.py‎

Copy file name to clipboardExpand all lines: python/tests/test_high_level.py
+33Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1509,3 +1509,36 @@ def raises(_val):
15091509
egraph = EGraph()
15101510
with pytest.raises(ValueError, match=msg):
15111511
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()

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.