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
8 changes: 8 additions & 0 deletions python/tvm_ffi/container.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,6 +192,10 @@ def __contains__(self, value: object) -> bool:
"""Check if the array contains a value."""
return _ffi_api.ArrayContains(self, value)

def __bool__(self) -> bool:
"""Return True if the array is non-empty."""
return len(self) > 0

def __add__(self, other: Iterable[T]) -> Array[T]:
"""Concatenate two arrays."""
return type(self)(itertools.chain(self, other))
Expand Down Expand Up @@ -337,6 +341,10 @@ def __len__(self) -> int:
"""Return the number of items in the map."""
return _ffi_api.MapSize(self)

def __bool__(self) -> bool:
"""Return True if the map is non-empty."""
return len(self) > 0

def __iter__(self) -> Iterator[K]:
"""Iterate over the map's keys."""
return iter(self.keys())
Expand Down
28 changes: 28 additions & 0 deletions tests/python/test_container.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,3 +227,31 @@ def test_large_map_get() -> None:
def test_array_contains(arr: list[Any], value: Any, expected: bool) -> None:
a = tvm_ffi.convert(arr)
assert (value in a) == expected


@pytest.mark.parametrize(
"arr, expected",
[
([1, 2, 3], True),
([1], True),
([], False),
(["hello"], True),
],
)
def test_array_bool(arr: list[Any], expected: bool) -> None:
a = tvm_ffi.Array(arr)
assert bool(a) is expected


@pytest.mark.parametrize(
"mapping, expected",
[
({"a": 1, "b": 2}, True),
({"a": 1}, True),
({}, False),
({1: "one"}, True),
],
)
def test_map_bool(mapping: dict[Any, Any], expected: bool) -> None:
m = tvm_ffi.Map(mapping)
assert bool(m) is expected