[Mlir-commits] [mlir] [MLIR][Python] Make Python-defined dialect loading context-aware (PR #210501)

llvmlistbot at llvm.org llvmlistbot at llvm.org
Thu Jul 23 03:10:46 PDT 2026


================
@@ -957,18 +957,11 @@ def _emit_module(cls) -> ir.Module:
         return m
 
     @classmethod
-    def load(
-        cls,
-        *,
-        reload: bool = False,
-    ) -> None:
-        if hasattr(cls, "_mlir_module") and not reload:
-            if cls._mlir_module.context is not ir.Context.current:
-                raise RuntimeError(
-                    "This dialect was loaded in a different context. "
-                    "Please set reload=True to reload the dialect in the current context."
-                )
-            return
+    def load(cls) -> None:
+        if ir.Context.current.is_dialect_loaded(cls.DIALECT_NAMESPACE):
+            raise RuntimeError(
----------------
PragmaTwice wrote:

> Could the load just do nothing and return?

That's quite tricky.

Let me share an example about why "do nothing" may actually not be what users want:
```python
class  MyDialect(Dialect):
  ...

class Op1(MyDialect.Operation):
  ...

c = Context()
with c:
  MyDialect.load() # first time to load

class Op2(MyDialect.Operation):
  ...

with c:
  MyDialect.load() # second time to load: should Op2 be loaded?
```

Note that in the second time, user may expect that `Op2` is loaded into the dialect!

And if the context is changed in the second time, then everything works fine (we actually have some test cases in such pattern).

```
class  MyDialect(Dialect):
  ...

class Op1(MyDialect.Operation):
  ...

with Context():
  MyDialect.load() # first time to load: just Op1

class Op2(MyDialect.Operation):
  ...

with Context():
  MyDialect.load() # second time to load: Op1 and Op2
```

> if you want to keep current approach, could it raise more specific exception like DialectReloadingError or DialectAlreadyLoadedError?

Sure.

https://github.com/llvm/llvm-project/pull/210501


More information about the Mlir-commits mailing list