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
16 changes: 15 additions & 1 deletion docs/reference/block.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,21 @@

# Block

`Block` is shallowly immutable: its backing tuple cannot be reassigned or deleted,
and instances have no writable `__dict__`. Operations return new blocks.
Objects stored in a block retain their own mutability:

```python
from expression.collections import Block

items = Block([[]])
items[0].append(42) # The contained list is still mutable.
```

These protections prevent ordinary attribute mutation; they do not prevent
deliberate bypasses such as `object.__setattr__`.

```{eval-rst}
.. automodule:: expression.collections.block
:members:
```
```
20 changes: 19 additions & 1 deletion docs/reference/map.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,25 @@

# Map

`Map` is shallowly immutable: its tree reference and internal tree nodes cannot
be reassigned or deleted through ordinary attribute access. Instances and tree
nodes have no writable `__dict__`. Updates return new maps and safely share
unchanged nodes with earlier maps:

```python
from expression.collections import Map

original = Map.create([(1, "one")])
updated = original.add(2, "two")
assert 2 not in original
assert updated[2] == "two"
```

Keys and values retain their own mutability. Keys must keep stable comparison
behavior, and hashing a map requires keys and values with stable hashes.
These protections do not prevent deliberate bypasses such as `object.__setattr__`.

```{eval-rst}
.. automodule:: expression.collections.map
:members:
```
```
6 changes: 5 additions & 1 deletion expression/collections/block.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import functools
import itertools
from collections.abc import Callable, Collection, Iterable, Iterator, Sequence
from dataclasses import dataclass
from typing import TYPE_CHECKING, Any, Literal, TypeVar, get_args, overload

from typing_extensions import TypeVarTuple, Unpack
Expand Down Expand Up @@ -60,6 +61,7 @@
_P = TypeVarTuple("_P")


@dataclass(frozen=True, slots=True, weakref_slot=True, init=False, eq=False, repr=False)
class Block(
Collection[_TSource], # Sequence breaks pydantic
PipeMixin,
Expand All @@ -83,10 +85,12 @@ class Block(

__match_args__ = ("_value",)

_value: tuple[_TSource, ...]

def __init__(self, value: Iterable[_TSource] = ()) -> None:
# Use composition instead of inheritance since generic tuples
# are not suppored by mypy.
self._value: tuple[_TSource, ...] = tuple(value) if value else tuple()
object.__setattr__(self, "_value", tuple(value) if value else tuple())

def append(self, other: Block[_TSource]) -> Block[_TSource]:
"""Append other block to end of the block."""
Expand Down
6 changes: 5 additions & 1 deletion expression/collections/map.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from __future__ import annotations

from collections.abc import Callable, ItemsView, Iterable, Iterator, Mapping
from dataclasses import dataclass
from typing import Any, TypeVar, cast

from expression.core import Option, PipeMixin, curry_flip, pipe
Expand All @@ -40,11 +41,14 @@
_T6 = TypeVar("_T6")


@dataclass(frozen=True, slots=True, weakref_slot=True, init=False, eq=False, repr=False, match_args=False)
class Map(Mapping[_Key, _Value], PipeMixin):
"""The immutable map class."""

_tree: MapTree[_Key, _Value]

def __init__(self, __tree: MapTree[_Key, _Value] | None = None) -> None:
self._tree: MapTree[_Key, _Value] = __tree if __tree else maptree.empty
object.__setattr__(self, "_tree", __tree if __tree else maptree.empty)

def add(self, key: _Key, value: _Value) -> Map[_Key, _Value]:
return Map(maptree.add(key, value, self._tree))
Expand Down
4 changes: 2 additions & 2 deletions expression/collections/maptree.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@
Result = TypeVar("Result")


@dataclass
@dataclass(frozen=True, slots=True)
class MapTreeLeaf(Generic[Key, Value]):
key: Key
value: Value
Expand All @@ -48,7 +48,7 @@ class MapTreeLeaf(Generic[Key, Value]):
MapTree = Option[MapTreeLeaf[Key, Value]]


@dataclass
@dataclass(frozen=True, slots=True)
class MapTreeNode(MapTreeLeaf[Key, Value]):
left: MapTree[Key, Value]
right: MapTree[Key, Value]
Expand Down
2 changes: 2 additions & 0 deletions expression/core/pipe.py
Original file line number Diff line number Diff line change
Expand Up @@ -414,6 +414,8 @@ def starpipe(args: Any, /, *fns: Callable[..., Any]) -> Any:
class PipeMixin:
"""A pipe mixin class that enabled a class to use pipe fluently."""

__slots__ = ()

@overload
def pipe(self: _A, fn1: Callable[[_A], _B], /) -> _B: ...

Expand Down
38 changes: 38 additions & 0 deletions tests/test_block.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,14 @@
import copy
import functools
import pickle
import weakref
from dataclasses import FrozenInstanceError
from builtins import list as list
from collections.abc import Callable
from typing import Any, List, Annotated

import pytest

from hypothesis import given # type: ignore
from hypothesis import strategies as st
from pydantic import BaseModel, Field, GetCoreSchemaHandler
Expand All @@ -14,6 +20,38 @@
Func = Callable[[int], int]


def test_block_backing_state_is_frozen():
xs = Block([1, 2])
with pytest.raises(FrozenInstanceError):
setattr(xs, "_value", (9,))
with pytest.raises(FrozenInstanceError):
delattr(xs, "_value")
assert not hasattr(xs, "__dict__")
assert list(xs) == [1, 2]


def test_block_immutability_is_shallow():
item: list[int] = []
source = [item]
xs = Block(source)
source.clear()
item.append(42)
assert list(xs) == [[42]]


def test_block_frozen_copy_and_pickle():
xs = Block[int]([1, 2])
assert weakref.ref(xs)() is xs
for restored in (copy.copy(xs), copy.deepcopy(xs), pickle.loads(pickle.dumps(xs))):
assert restored == xs
assert repr(restored) == repr(xs)
assert not hasattr(restored, "__dict__")
with pytest.raises(FrozenInstanceError):
setattr(restored, "_value", ())
with pytest.raises(TypeError):
hash(xs)


@given(st.integers(min_value=0, max_value=10000)) # type: ignore
def test_block_large_list(x: int):
xs = block.of_seq(range(x))
Expand Down
58 changes: 58 additions & 0 deletions tests/test_map.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,68 @@
import copy
import pickle
import weakref
from collections.abc import Callable, ItemsView, Iterable
from dataclasses import FrozenInstanceError

import pytest

from hypothesis import given # type: ignore
from hypothesis import strategies as st

from expression import Some, pipe
from expression.collections import Block, Map, map
from expression.collections.maptree import MapTreeLeaf, MapTreeNode, empty


def test_map_backing_state_is_frozen():
xs = map.create([(1, "one")])
with pytest.raises(FrozenInstanceError):
setattr(xs, "_tree", empty)
with pytest.raises(FrozenInstanceError):
delattr(xs, "_tree")
assert not hasattr(xs, "__dict__")
assert xs[1] == "one"


def test_map_shared_nodes_are_frozen():
leaf = MapTreeLeaf(1, "one")
a = Map[int, str](Some(leaf))
b = a.add(2, "two")
for field, replacement in (("key", 9), ("value", "changed")):
with pytest.raises(FrozenInstanceError):
setattr(leaf, field, replacement)
with pytest.raises(FrozenInstanceError):
delattr(leaf, field)
assert not hasattr(leaf, "__dict__")
assert a[1] == b[1] == "one"


def test_map_branch_structure_is_frozen():
node = MapTreeNode(1, "one", empty, empty, 2)
for field in ("key", "value", "left", "right", "height"):
with pytest.raises(FrozenInstanceError):
setattr(node, field, None)
with pytest.raises(FrozenInstanceError):
delattr(node, field)
assert not hasattr(node, "__dict__")


def test_map_frozen_copy_and_pickle():
xs = Map[int, str].create([(1, "one"), (2, "two")])
assert weakref.ref(xs)() is xs
for restored in (copy.copy(xs), copy.deepcopy(xs), pickle.loads(pickle.dumps(xs))):
assert restored == xs
assert hash(restored) == hash(xs)
assert not hasattr(restored, "__dict__")
with pytest.raises(FrozenInstanceError):
setattr(restored, "_tree", empty)


def test_map_immutability_is_shallow():
item: list[int] = []
xs = map.create([(1, item)])
item.append(42)
assert xs[1] == [42]


def test_map_empty():
Expand Down
Loading