[Mlir-commits] [mlir] [MLIR][Python] Add get_parent_of_type helper (PR #185512)
Jakub Kuderski
llvmlistbot at llvm.org
Mon Mar 9 13:49:49 PDT 2026
================
@@ -21,6 +21,33 @@
)
+def get_parent_of_type(
+ op: "OpView | Operation", op_class: "type[OpView]"
+) -> "OpView | None":
+ """Return the closest enclosing parent operation of the given type.
+
+ Walks the parent chain of *op* and returns the first ancestor that is an instance of *op_class*.
+ Returns ``None`` if no matching parent is found.
+
+ Args:
+ op: The starting operation.
+ op_class: The OpView subclass to search for (e.g. ``func.FuncOp``).
+
+ """
+ if not (isinstance(op_class, type) and issubclass(op_class, OpView)):
+ raise TypeError(f"op_class must be an OpView subclass, got {op_class!r}")
+ try:
+ parent = op.operation.parent
----------------
kuhar wrote:
Why do we need the first parent? checked in a try block?
I thought that something like this should work:
```py
while op := op.parent:
if isinstance(op.opview, op_class):
return op.opview
return None
```
?
If we do need it, can we have a test case that shows why?
https://github.com/llvm/llvm-project/pull/185512
More information about the Mlir-commits
mailing list