You are viewing a plain text version of this content. The canonical link for it is here.
Posted to discuss-archive@tvm.apache.org by "junrushao (via GitHub)" <gi...@apache.org> on 2026/04/10 16:31:23 UTC
[PR] fix(py_class): support `super().__init__()` in `init=False` subclasses [tvm-ffi]
junrushao opened a new pull request, #532:
URL: https://github.com/apache/tvm-ffi/pull/532
## Summary
- Fix segfault when `@py_class(init=False)` subclasses use `super().__init__()` followed by field assignment
- Add `ffi.NewEmpty` C++ function to allocate zero-initialized objects by type index
- Detect super-init-from-subclass pattern in `_make_init()` and pre-allocate instead of dispatching to `__ffi_init__`
## Motivation
The common Python pattern of defining a custom `__init__` that calls `super().__init__()` then sets fields crashes when used with `@py_class(init=False)`:
```python
@py_class(init=False)
class PointerType(Node):
element_type: Object
def __init__(self, element_type):
super().__init__() # parent's auto-init dispatches to child's C++ ctor → crash
self.element_type = element_type
```
The parent's auto-generated `__init__` forwards to `__ffi_init__` using the child type's C++ constructor, which expects field arguments that were not provided.
## Design
**C++ side** (`src/ffi/extra/dataclass.cc`): Register `ffi.NewEmpty(type_index) -> ObjectRef` that allocates a zero-initialized object via `CreateEmptyObject`. The calloc'd state is valid: `None` for `Any`/`ObjectRef` fields, `0` for scalars.
**Python side** (`python/tvm_ffi/registry.py`):
- `_ffi_alloc_empty(obj)`: Calls `ffi.NewEmpty` to allocate an empty FFI object for `type(obj)` and moves the handle into `obj`. No-op if already allocated.
- `_is_super_init_from_subclass(self)`: Compares `type(self).__tvm_ffi_type_info__` identity against the declaring class's `type_info`. Returns `True` only for registered `@py_class` subclasses — undecorated subclasses inherit the parent's `type_info` so the identity check correctly filters them out.
- Both `_make_init` code paths (with/without `__post_init__`) intercept the no-args super-init-from-subclass call and allocate an empty object instead of dispatching to `__ffi_init__`.
## Test plan
- [x] `uv run pytest -vvs tests/python/test_dataclass_py_class.py::TestSuperInitPattern` — 12 tests pass
- [x] `uv run pytest -vvs tests/python/` — 1970 passed, 38 skipped, 3 xfailed, 0 failures
Tests cover: basic super-init, deep hierarchy (Node→BaseType→PointerType), calloc defaults, intermediate custom/auto inits, normal init unaffected, non-py_class subclass error handling, isinstance checks, field overwrite, copy/deepcopy, and direct-from-Object inheritance.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] fix(py_class): support `super().__init__()` in `init=False` subclasses [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #532:
URL: https://github.com/apache/tvm-ffi/pull/532#discussion_r3065564005
##########
python/tvm_ffi/registry.py:
##########
@@ -507,6 +540,21 @@ def _install_init(cls: type, *, enabled: bool) -> None:
``__init__``.
"""
if "__init__" in cls.__dict__:
+ if not enabled:
+ # Wrap user's __init__ to pre-allocate the C++ object so that
+ # field setters work immediately (the calloc'd object is valid:
+ # None for Any/ObjectRef fields, 0 for scalars).
+ user_init = cls.__dict__["__init__"]
+
+ def __init__(self: Any, *args: Any, **kwargs: Any) -> None:
+ actual_type_info = type(self).__tvm_ffi_type_info__
+ _ffi_alloc_empty(self, actual_type_info.type_index)
+ user_init(self, *args, **kwargs)
+
+ __init__.__qualname__ = user_init.__qualname__
+ __init__.__module__ = getattr(user_init, "__module__", None) # type: ignore[assignment]
+ __init__.__wrapped__ = user_init # type: ignore[assignment]
+ setattr(cls, "__init__", __init__)
Review Comment:

To simplify the code and ensure all metadata from the original `__init__` is preserved (like `__doc__` and `__annotations__`), you can use `functools.wraps`. This makes the wrapper more robust for introspection.
```suggestion
def __init__(self: Any, *args: Any, **kwargs: Any) -> None:
actual_type_info = type(self).__tvm_ffi_type_info__
_ffi_alloc_empty(self, actual_type_info.type_index)
user_init(self, *args, **kwargs)
setattr(cls, "__init__", functools.wraps(user_init)(__init__))
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org
Re: [PR] fix(py_class): support `super().__init__()` in `init=False` subclasses [tvm-ffi]
Posted by "junrushao (via GitHub)" <gi...@apache.org>.
junrushao merged PR #532:
URL: https://github.com/apache/tvm-ffi/pull/532
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: discuss-archive-unsubscribe@tvm.apache.org
For additional commands, e-mail: discuss-archive-help@tvm.apache.org