diff --git a/include/tvm/ffi/c_api.h b/include/tvm/ffi/c_api.h index 0deb498ac..4d8a2f72a 100644 --- a/include/tvm/ffi/c_api.h +++ b/include/tvm/ffi/c_api.h @@ -70,7 +70,7 @@ /*! \brief TVM FFI minor version. */ #define TVM_FFI_VERSION_MINOR 1 /*! \brief TVM FFI patch version. */ -#define TVM_FFI_VERSION_PATCH 16 +#define TVM_FFI_VERSION_PATCH 17 // NOLINTEND(modernize-macro-to-enum) #ifdef __cplusplus diff --git a/python/tvm_ffi/cython/object.pxi b/python/tvm_ffi/cython/object.pxi index 3219158ff..6ea548d13 100644 --- a/python/tvm_ffi/cython/object.pxi +++ b/python/tvm_ffi/cython/object.pxi @@ -16,6 +16,7 @@ # under the License. import json from abc import ABCMeta +from cpython.type cimport PyType_Check, PyType_IsSubtype from typing import Any @@ -221,15 +222,51 @@ cdef class CContainerBase(CObject): self._dlpack_exchange_api = NULL +# Whether Object checks require ABCMeta's extended subclass machinery. +# Most Object classes use ordinary inheritance, so Python's faster MRO-based +# subtype checks suffice. Registering a virtual subclass or defining a custom +# __subclasshook__ enables ABCMeta checks for all Object classes thereafter. +cdef bint _OBJECT_USE_ABC_CHECKS = False + + class _ObjectSlotsMeta(ABCMeta): def __new__(mcls, name: str, bases: tuple[type, ...], ns: dict[str, Any], **kwargs: Any): + # Creates the class, defaulting to no additional instance slots. + global _OBJECT_USE_ABC_CHECKS if "__slots__" not in ns: ns["__slots__"] = () + # ABCMeta calls __subclasshook__ to customize subclass recognition: + # True/False decides the result; NotImplemented defers to normal ABC checks. + if "__subclasshook__" in ns: + _OBJECT_USE_ABC_CHECKS = True return super().__new__(mcls, name, bases, ns, **kwargs) def __init__(cls, name: str, bases: tuple[type, ...], ns: dict[str, Any], **kwargs: Any): + # Initializes the newly created class through ABCMeta. super().__init__(name, bases, ns, **kwargs) + def register(cls, subclass): + # Registers a virtual subclass without changing its inheritance or MRO. + global _OBJECT_USE_ABC_CHECKS + _OBJECT_USE_ABC_CHECKS = True + return ABCMeta.register(cls, subclass) + + def __instancecheck__(cls, instance): + # Implements isinstance(instance, cls). + if _OBJECT_USE_ABC_CHECKS: + return ABCMeta.__instancecheck__(cls, instance) + if PyType_IsSubtype(type(instance), cls): + return True + return type.__instancecheck__(cls, instance) # a ``__class__`` other than the type + + def __subclasscheck__(cls, subclass): + # Implements issubclass(subclass, cls). + if _OBJECT_USE_ABC_CHECKS: + return ABCMeta.__subclasscheck__(cls, subclass) + if PyType_Check(subclass): + return PyType_IsSubtype(subclass, cls) + return type.__subclasscheck__(cls, subclass) + class Object(CObject, metaclass=_ObjectSlotsMeta): """Base class of all TVM FFI objects. diff --git a/tests/python/test_object.py b/tests/python/test_object.py index 23df2d5c2..d38a71c50 100644 --- a/tests/python/test_object.py +++ b/tests/python/test_object.py @@ -16,6 +16,7 @@ # under the License. from __future__ import annotations +import subprocess import sys from collections.abc import Sequence from typing import Any @@ -477,6 +478,46 @@ def test_issubclass_user_type_is_object(self) -> None: assert issubclass(tvm_ffi.testing.TestObjectBase, tvm_ffi.Object) assert issubclass(tvm_ffi.testing.TestObjectDerived, tvm_ffi.Object) + def test_non_object_values(self) -> None: + """Values and classes outside the hierarchy are no Object, and a non-class is refused.""" + for value in (1, "a", None, [1], object()): + assert not isinstance(value, tvm_ffi.Object) + assert not isinstance(value, tvm_ffi.testing.TestObjectBase) + assert not issubclass(int, tvm_ffi.Object) + with pytest.raises(TypeError): + issubclass(1, tvm_ffi.Object) # type: ignore[arg-type] + + def test_containers_keep_their_collection_abcs(self) -> None: + """The collections.abc bases of a container answer as before.""" + assert isinstance(tvm_ffi.Array([1]), Sequence) + assert not isinstance(tvm_ffi.Map({"a": 1}), Sequence) + + def test_virtual_subclass_after_register(self) -> None: + """``register`` and ``__subclasshook__`` keep ABCMeta's meaning, from the first one on. + + Each runs in its own process: it switches the checks of every Object class there to ABCMeta's. + """ + register = ( + "import tvm_ffi.testing as t\n" + "class Virtual: pass\n" + "assert not isinstance(Virtual(), t.TestObjectBase)\n" + "t.TestObjectBase.register(Virtual)\n" + "assert isinstance(Virtual(), t.TestObjectBase) and issubclass(Virtual, t.TestObjectBase)\n" + "assert not isinstance(Virtual(), t.TestObjectDerived)\n" + "assert isinstance(t.TestObjectBase(), t.TestObjectBase)\n" + ) + hook = ( + "import tvm_ffi\n" + "class Hooked(tvm_ffi.Object):\n" + " @classmethod\n" + " def __subclasshook__(cls, other):\n" + " return True if other is int else NotImplemented\n" + "assert issubclass(int, Hooked) and isinstance(1, Hooked)\n" + "assert not issubclass(str, Hooked)\n" + ) + for code in (register, hook): + subprocess.run([sys.executable, "-c", code], check=True) + def test_issubclass_sibling_containers(self) -> None: """Sibling container types should not be subclasses of each other.""" assert not issubclass(tvm_ffi.List, tvm_ffi.Array)