Skip to content

feat(core): Support freezing List/Dict #58

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 23, 2025
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: 2 additions & 0 deletions include/mlc/c_api.h
Original file line number Diff line number Diff line change
Expand Up @@ -163,13 +163,15 @@ typedef struct {
MLCAny _mlc_header;
int64_t capacity;
int64_t size;
int8_t frozen;
void *data;
} MLCList;

typedef struct {
MLCAny _mlc_header;
int64_t capacity;
int64_t size;
int8_t frozen;
void *data;
} MLCDict;

Expand Down
2 changes: 2 additions & 0 deletions include/mlc/core/dict.h
Original file line number Diff line number Diff line change
Expand Up @@ -145,8 +145,10 @@ struct UDict : public ObjectRef {
MLC_DEF_OBJ_REF(MLC_EXPORTS, UDict, UDictObj, ObjectRef)
.Field("capacity", &MLCDict::capacity, /*frozen=*/true)
.Field("size", &MLCDict::size, /*frozen=*/true)
.Field("_frozen", &MLCDict::frozen, /*frozen=*/false)
.Field("data", &MLCDict::data, /*frozen=*/true)
.StaticFn("__init__", FromAnyTuple)
.MemFn("_clear", &UDictObj::clear)
.MemFn("__str__", &UDictObj::__str__)
.MemFn("__getitem__", ::mlc::core::DictBase::Accessor<UDictObj>::GetItem)
.MemFn("__setitem__", ::mlc::core::DictBase::Accessor<UDictObj>::SetItem)
Expand Down
1 change: 1 addition & 0 deletions include/mlc/core/dict_base.h
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ inline DictBase::DictBase(int64_t capacity) : MLCDict() {
int64_t num_blocks = capacity / DictBase::kBlockCapacity;
this->MLCDict::capacity = capacity;
this->MLCDict::size = 0;
this->MLCDict::frozen = 0;
this->MLCDict::data = ::mlc::base::PODArrayCreate<Block>(num_blocks).release();
Block *blocks = this->Blocks();
for (int64_t i = 0; i < num_blocks; ++i) {
Expand Down
3 changes: 2 additions & 1 deletion include/mlc/core/list.h
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,9 @@ struct UList : public ObjectRef {
::mlc::core::ListBase::Accessor<UListObj>::New(num_args, args, ret);
}
MLC_DEF_OBJ_REF(MLC_EXPORTS, UList, UListObj, ObjectRef)
.Field("size", &MLCList::size, /*frozen=*/true)
.Field("capacity", &MLCList::capacity, /*frozen=*/true)
.Field("size", &MLCList::size, /*frozen=*/true)
.Field("_frozen", &MLCList::frozen, /*frozen=*/false)
.Field("data", &MLCList::data, /*frozen=*/true)
.StaticFn("__init__", FromAnyTuple)
.MemFn("__str__", &UListObj::__str__)
Expand Down
3 changes: 3 additions & 0 deletions include/mlc/core/list_base.h
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ struct ListBase : public MLCList {
MLC_INLINE ListBase::ListBase() : MLCList() {
this->MLCList::capacity = 0;
this->MLCList::size = 0;
this->MLCList::frozen = 0;
this->MLCList::data = nullptr;
}

Expand All @@ -62,6 +63,7 @@ MLC_INLINE ListBase::ListBase(std::initializer_list<Any> init) : ListBase() {
this->MLCList::data = ::mlc::base::PODArrayCreate<MLCAny>(numel).release();
this->MLCList::capacity = numel;
this->MLCList::size = 0;
this->MLCList::frozen = 0;
this->Replace(0, 0, numel, elems.data());
}

Expand All @@ -71,6 +73,7 @@ template <typename Iter> MLC_INLINE ListBase::ListBase(Iter first, Iter last) :
this->MLCList::data = ::mlc::base::PODArrayCreate<MLCAny>(numel).release();
this->MLCList::capacity = numel;
this->MLCList::size = 0;
this->MLCList::frozen = 0;
this->Replace(0, 0, numel, elems.data());
}

Expand Down
206 changes: 110 additions & 96 deletions python/mlc/_cython/core.pyx

Large diffs are not rendered by default.

22 changes: 22 additions & 0 deletions python/mlc/core/dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ class DictMeta(MetaNoSlots, ABCMeta): ...
class Dict(Object, Mapping[K, V], metaclass=DictMeta):
capacity: int
size: int
_frozen: int
data: Ptr

def __init__(
Expand Down Expand Up @@ -79,16 +80,30 @@ def values(self) -> ValuesView[V]:
def items(self) -> ItemsView[K, V]:
return _DictItemsView(self)

def freeze(self) -> None:
if self._frozen == 0:
self._frozen = 1

@property
def frozen(self) -> bool:
return self._frozen == 1

def __getitem__(self, key: K) -> V:
return Dict._C(b"__getitem__", self, key)

def __setitem__(self, key: K, value: V) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen dict")
Dict._C(b"__setitem__", self, key, value)

def __delitem__(self, key: K) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen dict")
Dict._C(b"__delitem__", self, key)

def pop(self, key: K, default: T | _UnspecifiedType = Unspecified) -> V | T:
if self._frozen:
raise RuntimeError("Cannot modify a frozen dict")
try:
return Dict._C(b"__delitem__", self, key)
except KeyError:
Expand All @@ -98,12 +113,19 @@ def pop(self, key: K, default: T | _UnspecifiedType = Unspecified) -> V | T:
return default

def setdefault(self, key: K, default: V | None = None) -> V | None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen dict")
try:
return self[key]
except KeyError:
self[key] = default # type: ignore[assignment]
return default

def clear(self) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen dict")
Dict._C(b"_clear", self)

# Additional methods required by the Mapping ABC
def __contains__(self, key: object) -> bool:
try:
Expand Down
23 changes: 23 additions & 0 deletions python/mlc/core/list.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class ListMeta(MetaNoSlots, ABCMeta): ...
class List(Object, Sequence[T], metaclass=ListMeta):
capacity: int
size: int
_frozen: int
data: Ptr

def __init__(self, iterable: Iterable[T] = ()) -> None:
Expand All @@ -26,6 +27,14 @@ def __init__(self, iterable: Iterable[T] = ()) -> None:
def __len__(self) -> int:
return self.size

def freeze(self) -> None:
if self._frozen == 0:
self._frozen = 1

@property
def frozen(self) -> bool:
return self._frozen == 1

@overload
def __getitem__(self, i: int) -> T: ...

Expand All @@ -44,6 +53,8 @@ def __getitem__(self, i: int | slice) -> T | Sequence[T]:
raise TypeError(f"list indices must be integers or slices, not {type(i).__name__}")

def __setitem__(self, index: int, value: T) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
length = len(self)
if not -length <= index < length:
raise IndexError(f"list assignment index out of range: {index}")
Expand All @@ -69,20 +80,30 @@ def __radd__(self, other: Sequence[T]) -> List[T]:
return result

def insert(self, i: int, x: T) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
i = _normalize_index(i, len(self) + 1)
return List._C(b"_insert", self, i, x)

def append(self, x: T) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
return List._C(b"_append", self, x)

def pop(self, i: int = -1) -> T:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
i = _normalize_index(i, len(self))
return List._C(b"_pop", self, i)

def clear(self) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
return List._C(b"_clear", self)

def extend(self, iterable: Iterable[T]) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
return List._C(b"_extend", self, *iterable)

def __eq__(self, other: Any) -> bool:
Expand All @@ -98,6 +119,8 @@ def __ne__(self, other: Any) -> bool:
return not (self == other)

def __delitem__(self, i: int) -> None:
if self._frozen:
raise RuntimeError("Cannot modify a frozen list")
self.pop(i)

def py(self) -> list[T]:
Expand Down
2 changes: 1 addition & 1 deletion python/mlc/dataclasses/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ def _get_num_bytes(field_ty: Any) -> int:
d_fields: list[Field] = []
for type_field in type_fields:
lhs = type_field.name
if lhs.startswith("_"):
if lhs.startswith("_mlc_"):
continue
rhs = getattr(type_cls, lhs, MISSING)
if isinstance(rhs, property):
Expand Down
22 changes: 22 additions & 0 deletions tests/python/test_core_dict.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
from collections.abc import Callable

import pytest
from mlc import Dict

Expand Down Expand Up @@ -133,3 +135,23 @@ def test_dict_to_py_1() -> None:
assert isinstance(a["a"]["c"], float) and a["a"]["c"] == 3.0
assert isinstance(a[1], str) and a[1] == "one"
assert isinstance(a[None], str) and a[None] == "e"


@pytest.mark.parametrize(
"callable",
[
lambda a: a.__setitem__(0, 0),
lambda a: a.__delitem__(1),
lambda a: a.pop(2),
lambda a: a.clear(),
lambda a: a.setdefault(1, 5),
],
)
def test_dict_freeze(callable: Callable[[Dict], None]) -> None:
a = Dict({i: i * i for i in range(1, 5)})
assert a.frozen == False
a.freeze()
assert a.frozen == True
with pytest.raises(RuntimeError) as e:
callable(a)
assert str(e.value) == "Cannot modify a frozen dict"
24 changes: 23 additions & 1 deletion tests/python/test_core_list.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from collections.abc import Sequence
from collections.abc import Callable, Sequence
from typing import Any

import pytest
Expand Down Expand Up @@ -254,3 +254,25 @@ def test_list_to_py_1() -> None:
assert a[2] == 1 and type(a[2]) is int
assert a[3] == 2.0 and type(a[3]) is float
assert a[4] == "anything" and type(a[4]) is str


@pytest.mark.parametrize(
"callable",
[
lambda a: a.append(4),
lambda a: a.insert(0, 0),
lambda a: a.pop(0),
lambda a: a.clear(),
lambda a: a.extend([4, 5, 6]),
lambda a: a.__setitem__(0, 0),
lambda a: a.__delitem__(0),
],
)
def test_list_freeze(callable: Callable[[List], None]) -> None:
a = List([1, 2, 3])
assert a.frozen == False
a.freeze()
assert a.frozen == True
with pytest.raises(RuntimeError) as e:
callable(a)
assert str(e.value) == "Cannot modify a frozen list"
54 changes: 54 additions & 0 deletions tests/python/test_dataclasses_py_class.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,18 @@ class Frozen(mlcd.PyClass):
b: str


@mlcd.py_class
class ContainerFields(mlcd.PyClass):
a: list[int]
b: dict[int, int]


@mlcd.py_class(frozen=True)
class FrozenContainerFields(mlcd.PyClass):
a: list[int]
b: dict[int, int]


def test_base() -> None:
base = Base(1, "a")
base_str = "mlc.testing.py_class_base(base_a=1, base_b='a')"
Expand Down Expand Up @@ -164,3 +176,45 @@ def test_derived_derived() -> None:
assert str(obj) == (
"mlc.testing.DerivedDerived(base_a=1, base_b=[1, 2], derived_a=2, derived_b='b', derived_derived_a='a')"
)


def test_container_fields() -> None:
obj_0 = ContainerFields([1, 2], {1: 2})
assert obj_0.a == [1, 2]
assert obj_0.b == {1: 2}

obj_1 = ContainerFields(a=obj_0.a, b=obj_0.b)
assert obj_1.a == obj_0.a
assert obj_1.b == obj_0.b


def test_frozen_container_fields() -> None:
obj = FrozenContainerFields([1, 2], {1: 2})
assert obj.a == [1, 2]
assert obj.b == {1: 2}

assert obj.a.frozen
assert obj.b.frozen

e: pytest.ExceptionInfo
with pytest.raises(AttributeError) as e:
obj.a = [2, 3]
assert str(e.value) in [
"property 'a' of 'FrozenContainerFields' object has no setter",
"can't set attribute",
]

with pytest.raises(AttributeError) as e:
obj.b = {2: 3}
assert str(e.value) in [
"property 'b' of 'FrozenContainerFields' object has no setter",
"can't set attribute",
]

with pytest.raises(RuntimeError) as e:
obj.a[0] = 3
assert str(e.value) == "Cannot modify a frozen list"

with pytest.raises(RuntimeError) as e:
obj.b[0] = 3
assert str(e.value) == "Cannot modify a frozen dict"
Loading