diff --git a/mlir/lib/Bindings/Python/IRCore.cpp b/mlir/lib/Bindings/Python/IRCore.cpp --- a/mlir/lib/Bindings/Python/IRCore.cpp +++ b/mlir/lib/Bindings/Python/IRCore.cpp @@ -2094,6 +2094,7 @@ py::arg("successors") = py::none(), py::arg("regions") = 0, py::arg("loc") = py::none(), py::arg("ip") = py::none(), kOperationCreateDocstring) + .def("erase", [](PyOperation &self) { mlirOperationDestroy(self.get()); }) .def_property_readonly(MLIR_PYTHON_CAPI_PTR_ATTR, &PyOperation::getCapsule) .def(MLIR_PYTHON_CAPI_FACTORY_ATTR, &PyOperation::createFromCapsule) diff --git a/mlir/test/Bindings/Python/ir_operation.py b/mlir/test/Bindings/Python/ir_operation.py --- a/mlir/test/Bindings/Python/ir_operation.py +++ b/mlir/test/Bindings/Python/ir_operation.py @@ -646,3 +646,26 @@ assert m2 is m run(testCapsuleConversions) + +# CHECK-LABEL: TEST: testOperationDestroy +def testOperationDestroy(): + ctx = Context() + ctx.allow_unregistered_dialects = True + with Location.unknown(ctx): + m = Module.create() + with InsertionPoint(m.body): + op = Operation.create("custom.op1") + + # CHECK: "custom.op1" + print(m) + + op.operation.erase() + del op + + # CHECK-NOT: "custom.op1" + print(m) + + # Ensure we can create another operation + Operation.create("custom.op2") + +run(testOperationDestroy)