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
11 changes: 10 additions & 1 deletion src/unihttp/omitted.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, ClassVar, TypeAlias, TypeVar
from typing import Any, ClassVar, Self, TypeAlias, TypeVar


class SingletonMeta(type):
Expand All @@ -17,6 +17,15 @@ def __repr__(self) -> str:
def __bool__(self) -> bool:
return False

def __copy__(self) -> Self:
return self

def __deepcopy__(self, memo: dict[int, Any]) -> Self:
return self

def __reduce__(self) -> tuple[type[Self], tuple[()]]:
return (type(self), ())


T = TypeVar("T")
Omittable: TypeAlias = T | Omitted # noqa: UP040
63 changes: 63 additions & 0 deletions tests/test_features/test_omitted_identity.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import copy
import dataclasses
import pickle
from dataclasses import dataclass

from unihttp.omitted import Omittable, Omitted


def test_singleton_identity():
assert Omitted() is Omitted()


def test_copy_preserves_singleton():
o = Omitted()
assert copy.copy(o) is o
assert copy.copy(o) == o


def test_deepcopy_preserves_singleton():
o = Omitted()
assert copy.deepcopy(o) is o
assert copy.deepcopy(o) == o


def test_pickle_preserves_singleton():
o = Omitted()
restored = pickle.loads(pickle.dumps(o))
assert restored is o
assert restored == o


def test_deepcopy_memo_argument():
o = Omitted()
memo: dict[int, object] = {}
assert copy.deepcopy(o, memo) is o


@dataclass
class _Model:
name: str
optional: Omittable[str] = Omitted()


def test_dataclass_equality_survives_deepcopy():
a = _Model(name="a")
b = copy.deepcopy(a)
assert a == b
assert a.optional == b.optional


def test_dataclass_equality_survives_pickle():
a = _Model(name="a")
b = pickle.loads(pickle.dumps(a))
assert a == b
assert a.optional == b.optional


def test_asdict_deepcopy_keeps_singleton():
# dataclasses.asdict() deep-copies field values; the Omitted sentinel
# must remain the singleton so downstream equality checks still hold.
a = _Model(name="a")
dumped = dataclasses.asdict(a)
assert dumped["optional"] is Omitted()
Loading