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/17 23:53:08 UTC
[PR] feat(dataclass): add asdict, astuple, and match_args support [tvm-ffi]
junrushao opened a new pull request, #556:
URL: https://github.com/apache/tvm-ffi/pull/556
## Summary
Adds three stdlib-parity features to `tvm_ffi.dataclasses`:
1. **`asdict(obj, *, dict_factory=dict)`** — recursively converts a `@py_class` / `@c_class` instance to a plain Python `dict`. FFI containers (`Array`, `List`) recurse into `list`; (`Map`, `Dict`) recurse into `dict`, yielding JSON-ready output.
2. **`astuple(obj, *, tuple_factory=tuple)`** — the tuple analogue of `asdict`, with the same recursion rules.
3. **`match_args: bool = True`** parameter on `@py_class` and `@c_class` — sets `cls.__match_args__` to the tuple of positional `__init__` field names (`init=True and not kw_only`), enabling Python 3.10+ `match` statements. Skipped when the class body already defines `__match_args__`.
Semantics follow CPython's `dataclasses` module: `asdict`/`astuple` raise `TypeError` for types and non-dataclass values; kw-only fields (via `field(kw_only=True)`, decorator-level `kw_only=True`, or the `KW_ONLY` sentinel) are excluded from `__match_args__`.
## Design notes
- `_is_ffi_dataclass_instance` filters FFI container instances (`Array`, `List`, `Map`, `Dict`) from FFI dataclass instances — both share `__tvm_ffi_type_info__`, so the container isinstance-check runs first during recursion.
- `_set_match_args` walks the `TypeInfo.parent_type_info` chain in parent-first order, matching the order of the auto-generated `__init__` signature.
- Recursion uses an `_ATOMIC_TYPES` frozenset (mirroring stdlib `dataclasses._ATOMIC_TYPES`) for the fast path on immutable leaves.
## Test plan
- [x] `uv run pytest tests/python/` — 2184 passed, 38 skipped, 3 xfailed
- [x] `pre-commit run --files <touched files>` — all hooks pass (ruff, ty, format)
- [x] New coverage in `tests/python/test_dataclass_common.py`:
- `TestAsdict` (15 tests): basic, nested, inheritance, FFI Array/List/Map/Dict recursion, `dict_factory`, result independence, error paths
- `TestAstuple` (10 tests): basic, nested, recursion, `tuple_factory`, error paths
- `TestMatchArgs` (11 tests): defaults, `init=False`, kw_only (field / decorator / `KW_ONLY` sentinel), inheritance order, `match_args=False` opt-out, user-defined `__match_args__` override, c_class basic and inheritance
--
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] feat(dataclass): add asdict, astuple, and match_args support [tvm-ffi]
Posted by "junrushao (via GitHub)" <gi...@apache.org>.
junrushao commented on code in PR #556:
URL: https://github.com/apache/tvm-ffi/pull/556#discussion_r3104022160
##########
python/tvm_ffi/dataclasses/common.py:
##########
@@ -72,3 +91,155 @@ def replace(obj: Any, /, **changes: Any) -> Any:
still replaceable.
"""
return obj.__replace__(**changes)
+
+
+def _is_ffi_dataclass_instance(obj: Any) -> bool:
+ """Return True when *obj* is a ``@c_class`` / ``@py_class`` **instance** (not a type)."""
+ if isinstance(obj, type):
+ return False
+ return getattr(type(obj), "__tvm_ffi_type_info__", None) is not None
+
+
+def _asdict_inner( # noqa: PLR0911, PLR0912
+ obj: Any, dict_factory: Callable[..., Any]
+) -> Any:
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ # FFI containers are treated as their stdlib analogues so the result is
+ # plain Python data — handy for JSON serialisation, the main use case.
+ if isinstance(obj, (Array, List)):
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if isinstance(obj, (Map, Dict)):
+ return dict_factory(
+ [
+ (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
+ for k, v in obj.items()
+ ]
+ )
+ if _is_ffi_dataclass_instance(obj):
+ fs = fields(obj)
+ if dict_factory is dict:
+ return {f.name: _asdict_inner(getattr(obj, f.name), dict) for f in fs} # ty: ignore[invalid-argument-type]
+ return dict_factory(
+ [(f.name, _asdict_inner(getattr(obj, f.name), dict_factory)) for f in fs] # ty: ignore[invalid-argument-type]
+ )
+ if obj_type is list:
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if obj_type is dict:
+ return {
+ _asdict_inner(k, dict_factory): _asdict_inner(v, dict_factory) for k, v in obj.items()
+ }
+ if obj_type is tuple:
+ return tuple(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, tuple):
+ if hasattr(obj, "_fields"): # namedtuple
+ return obj_type(*[_asdict_inner(v, dict_factory) for v in obj])
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, dict):
+ if hasattr(obj_type, "default_factory"):
+ result = obj_type(obj.default_factory)
Review Comment:
Thanks — I looked into this, and the check is correct as-written: `hasattr(obj_type, "default_factory")` mirrors CPython stdlib `dataclasses._asdict_inner` verbatim, and `collections.defaultdict` exposes `default_factory` as a class-level `member_descriptor`, so the class-level `hasattr` returns True:
```python
>>> hasattr(collections.defaultdict, "default_factory")
True
>>> collections.defaultdict.default_factory
<member 'default_factory' of 'collections.defaultdict' objects>
```
Locked this in with a direct test in `b92e706` (`TestAsdict::test_defaultdict_preserved` / `TestAstuple::test_defaultdict_preserved`) that verifies the `defaultdict` factory survives the recursion.
##########
python/tvm_ffi/dataclasses/common.py:
##########
@@ -72,3 +91,155 @@ def replace(obj: Any, /, **changes: Any) -> Any:
still replaceable.
"""
return obj.__replace__(**changes)
+
+
+def _is_ffi_dataclass_instance(obj: Any) -> bool:
+ """Return True when *obj* is a ``@c_class`` / ``@py_class`` **instance** (not a type)."""
+ if isinstance(obj, type):
+ return False
+ return getattr(type(obj), "__tvm_ffi_type_info__", None) is not None
+
+
+def _asdict_inner( # noqa: PLR0911, PLR0912
+ obj: Any, dict_factory: Callable[..., Any]
+) -> Any:
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ # FFI containers are treated as their stdlib analogues so the result is
+ # plain Python data — handy for JSON serialisation, the main use case.
+ if isinstance(obj, (Array, List)):
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if isinstance(obj, (Map, Dict)):
+ return dict_factory(
+ [
+ (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
+ for k, v in obj.items()
+ ]
+ )
+ if _is_ffi_dataclass_instance(obj):
+ fs = fields(obj)
+ if dict_factory is dict:
+ return {f.name: _asdict_inner(getattr(obj, f.name), dict) for f in fs} # ty: ignore[invalid-argument-type]
+ return dict_factory(
+ [(f.name, _asdict_inner(getattr(obj, f.name), dict_factory)) for f in fs] # ty: ignore[invalid-argument-type]
+ )
+ if obj_type is list:
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if obj_type is dict:
+ return {
+ _asdict_inner(k, dict_factory): _asdict_inner(v, dict_factory) for k, v in obj.items()
+ }
+ if obj_type is tuple:
+ return tuple(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, tuple):
+ if hasattr(obj, "_fields"): # namedtuple
+ return obj_type(*[_asdict_inner(v, dict_factory) for v in obj])
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, dict):
+ if hasattr(obj_type, "default_factory"):
+ result = obj_type(obj.default_factory)
+ for k, v in obj.items():
+ result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory)
+ return result
+ return obj_type(
+ (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()
+ )
+ if issubclass(obj_type, list):
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ return copy.deepcopy(obj)
+
+
+def _astuple_inner(obj: Any, tuple_factory: Callable[..., Any]) -> Any: # noqa: PLR0911
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ if isinstance(obj, (Array, List)):
+ return [_astuple_inner(v, tuple_factory) for v in obj]
+ if isinstance(obj, (Map, Dict)):
+ return {
+ _astuple_inner(k, tuple_factory): _astuple_inner(v, tuple_factory)
+ for k, v in obj.items()
+ }
+ if _is_ffi_dataclass_instance(obj):
+ return tuple_factory(
+ [_astuple_inner(getattr(obj, f.name), tuple_factory) for f in fields(obj)] # ty: ignore[invalid-argument-type]
+ )
+ if isinstance(obj, tuple) and hasattr(obj, "_fields"): # namedtuple
+ return obj_type(*[_astuple_inner(v, tuple_factory) for v in obj])
+ if isinstance(obj, (list, tuple)):
+ return obj_type(_astuple_inner(v, tuple_factory) for v in obj)
+ if isinstance(obj, dict):
+ if hasattr(obj_type, "default_factory"):
+ result = obj_type(obj.default_factory)
Review Comment:
Same reasoning as above — the class-level `hasattr(obj_type, "default_factory")` check mirrors CPython stdlib and does catch `collections.defaultdict`, because `default_factory` is a class-level `member_descriptor`. Covered now by `TestAstuple::test_defaultdict_preserved` in `b92e706`.
--
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] feat(dataclass): add asdict, astuple, and match_args support [tvm-ffi]
Posted by "gemini-code-assist[bot] (via GitHub)" <gi...@apache.org>.
gemini-code-assist[bot] commented on code in PR #556:
URL: https://github.com/apache/tvm-ffi/pull/556#discussion_r3103983050
##########
python/tvm_ffi/dataclasses/common.py:
##########
@@ -72,3 +91,155 @@ def replace(obj: Any, /, **changes: Any) -> Any:
still replaceable.
"""
return obj.__replace__(**changes)
+
+
+def _is_ffi_dataclass_instance(obj: Any) -> bool:
+ """Return True when *obj* is a ``@c_class`` / ``@py_class`` **instance** (not a type)."""
+ if isinstance(obj, type):
+ return False
+ return getattr(type(obj), "__tvm_ffi_type_info__", None) is not None
+
+
+def _asdict_inner( # noqa: PLR0911, PLR0912
+ obj: Any, dict_factory: Callable[..., Any]
+) -> Any:
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ # FFI containers are treated as their stdlib analogues so the result is
+ # plain Python data — handy for JSON serialisation, the main use case.
+ if isinstance(obj, (Array, List)):
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if isinstance(obj, (Map, Dict)):
+ return dict_factory(
+ [
+ (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
+ for k, v in obj.items()
+ ]
+ )
+ if _is_ffi_dataclass_instance(obj):
+ fs = fields(obj)
+ if dict_factory is dict:
+ return {f.name: _asdict_inner(getattr(obj, f.name), dict) for f in fs} # ty: ignore[invalid-argument-type]
+ return dict_factory(
+ [(f.name, _asdict_inner(getattr(obj, f.name), dict_factory)) for f in fs] # ty: ignore[invalid-argument-type]
+ )
+ if obj_type is list:
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if obj_type is dict:
+ return {
+ _asdict_inner(k, dict_factory): _asdict_inner(v, dict_factory) for k, v in obj.items()
+ }
+ if obj_type is tuple:
+ return tuple(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, tuple):
+ if hasattr(obj, "_fields"): # namedtuple
+ return obj_type(*[_asdict_inner(v, dict_factory) for v in obj])
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, dict):
+ if hasattr(obj_type, "default_factory"):
+ result = obj_type(obj.default_factory)
+ for k, v in obj.items():
+ result[_asdict_inner(k, dict_factory)] = _asdict_inner(v, dict_factory)
+ return result
+ return obj_type(
+ (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory)) for k, v in obj.items()
+ )
+ if issubclass(obj_type, list):
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ return copy.deepcopy(obj)
+
+
+def _astuple_inner(obj: Any, tuple_factory: Callable[..., Any]) -> Any: # noqa: PLR0911
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ if isinstance(obj, (Array, List)):
+ return [_astuple_inner(v, tuple_factory) for v in obj]
+ if isinstance(obj, (Map, Dict)):
+ return {
+ _astuple_inner(k, tuple_factory): _astuple_inner(v, tuple_factory)
+ for k, v in obj.items()
+ }
+ if _is_ffi_dataclass_instance(obj):
+ return tuple_factory(
+ [_astuple_inner(getattr(obj, f.name), tuple_factory) for f in fields(obj)] # ty: ignore[invalid-argument-type]
+ )
+ if isinstance(obj, tuple) and hasattr(obj, "_fields"): # namedtuple
+ return obj_type(*[_astuple_inner(v, tuple_factory) for v in obj])
+ if isinstance(obj, (list, tuple)):
+ return obj_type(_astuple_inner(v, tuple_factory) for v in obj)
+ if isinstance(obj, dict):
+ if hasattr(obj_type, "default_factory"):
+ result = obj_type(obj.default_factory)
Review Comment:

The check `hasattr(obj_type, "default_factory")` is incorrect for `collections.defaultdict` because `default_factory` is an instance attribute, not a class attribute. This will cause `astuple` to fall through to the generic dict subclass handling, which will fail for `defaultdict` because its constructor requires the factory as the first argument. It should check the instance `obj` instead.
```suggestion
if hasattr(obj, "default_factory"):
result = obj_type(obj.default_factory)
```
##########
python/tvm_ffi/dataclasses/common.py:
##########
@@ -72,3 +91,155 @@ def replace(obj: Any, /, **changes: Any) -> Any:
still replaceable.
"""
return obj.__replace__(**changes)
+
+
+def _is_ffi_dataclass_instance(obj: Any) -> bool:
+ """Return True when *obj* is a ``@c_class`` / ``@py_class`` **instance** (not a type)."""
+ if isinstance(obj, type):
+ return False
+ return getattr(type(obj), "__tvm_ffi_type_info__", None) is not None
+
+
+def _asdict_inner( # noqa: PLR0911, PLR0912
+ obj: Any, dict_factory: Callable[..., Any]
+) -> Any:
+ obj_type = type(obj)
+ if obj_type in _ATOMIC_TYPES:
+ return obj
+ # FFI containers are treated as their stdlib analogues so the result is
+ # plain Python data — handy for JSON serialisation, the main use case.
+ if isinstance(obj, (Array, List)):
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if isinstance(obj, (Map, Dict)):
+ return dict_factory(
+ [
+ (_asdict_inner(k, dict_factory), _asdict_inner(v, dict_factory))
+ for k, v in obj.items()
+ ]
+ )
+ if _is_ffi_dataclass_instance(obj):
+ fs = fields(obj)
+ if dict_factory is dict:
+ return {f.name: _asdict_inner(getattr(obj, f.name), dict) for f in fs} # ty: ignore[invalid-argument-type]
+ return dict_factory(
+ [(f.name, _asdict_inner(getattr(obj, f.name), dict_factory)) for f in fs] # ty: ignore[invalid-argument-type]
+ )
+ if obj_type is list:
+ return [_asdict_inner(v, dict_factory) for v in obj]
+ if obj_type is dict:
+ return {
+ _asdict_inner(k, dict_factory): _asdict_inner(v, dict_factory) for k, v in obj.items()
+ }
+ if obj_type is tuple:
+ return tuple(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, tuple):
+ if hasattr(obj, "_fields"): # namedtuple
+ return obj_type(*[_asdict_inner(v, dict_factory) for v in obj])
+ return obj_type(_asdict_inner(v, dict_factory) for v in obj)
+ if issubclass(obj_type, dict):
+ if hasattr(obj_type, "default_factory"):
+ result = obj_type(obj.default_factory)
Review Comment:

The check `hasattr(obj_type, "default_factory")` is incorrect for `collections.defaultdict` because `default_factory` is an instance attribute, not a class attribute. This will cause `asdict` to fall through to the generic dict subclass handling, which will fail for `defaultdict` because its constructor requires the factory as the first argument. It should check the instance `obj` instead.
```suggestion
if hasattr(obj, "default_factory"):
result = obj_type(obj.default_factory)
```
--
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] feat(dataclass): add asdict, astuple, and match_args support [tvm-ffi]
Posted by "junrushao (via GitHub)" <gi...@apache.org>.
junrushao merged PR #556:
URL: https://github.com/apache/tvm-ffi/pull/556
--
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