Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion include/tvm/ffi/c_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
37 changes: 37 additions & 0 deletions python/tvm_ffi/cython/object.pxi
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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), <type>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(<type>subclass, <type>cls)
return type.__subclasscheck__(cls, subclass)


class Object(CObject, metaclass=_ObjectSlotsMeta):
"""Base class of all TVM FFI objects.
Expand Down
41 changes: 41 additions & 0 deletions tests/python/test_object.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
# under the License.
from __future__ import annotations

import subprocess
import sys
from collections.abc import Sequence
from typing import Any
Expand Down Expand Up @@ -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)
Expand Down
Loading