From 669052a9d29d5f357250182f319673f23bb39bd8 Mon Sep 17 00:00:00 2001 From: anticipate218 <3481402509@qq.com> Date: Mon, 16 Nov 2026 23:27:49 +0800 Subject: [PATCH] Fix slicing frozen Boxes --- AUTHORS.rst | 1 + CHANGES.rst | 5 +++ box/box.py | 12 ++---- test/test_box_slices.py | 83 +++++++++++++++++++++++++++++++++++++++++ 4 files changed, 93 insertions(+), 8 deletions(-) create mode 100644 test/test_box_slices.py diff --git a/AUTHORS.rst b/AUTHORS.rst index b2f08ec..e0280d1 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -128,3 +128,4 @@ Suggestions and bug reporting: - Mrunmayee Daware (Mrun25) - Peter Olkhovets (peterolkhov) +- anticipate218 diff --git a/CHANGES.rst b/CHANGES.rst index 826d748..dc69906 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -1,5 +1,10 @@ Changelog +Unreleased +---------- + +* Fixing non-empty slices of frozen Boxes raising BoxError instead of returning a frozen Box (thanks to anticipate218) + Version 8.0.1 ------------- diff --git a/box/box.py b/box/box.py index f2b539b..cbd7692 100644 --- a/box/box.py +++ b/box/box.py @@ -787,10 +787,8 @@ def __getitem__(self, item, _ignore_default=False): raise BoxKeyError("_box_config should only exist as an attribute and is never defaulted") from cause if isinstance(item, slice): # In Python 3.12 this changes to a KeyError instead of TypeError - new_box = self._box_config["box_class"](**self.__box_config()) - for x in list(super().keys())[item.start : item.stop : item.step]: - new_box[x] = self[x] - return new_box + keys = list(super().keys())[item] + return self._box_config["box_class"](((key, self[key]) for key in keys), **self.__box_config()) if self.__process_dotted_key(item): first_item, children = _parse_box_dots(self, item) first_item = self.__dots_int_key(first_item) @@ -813,10 +811,8 @@ def __getitem__(self, item, _ignore_default=False): raise BoxKeyError(str(err)) from _exception_cause(err) except TypeError as err: if isinstance(item, slice): # pragma: no cover (Python 3.11, slices became hashable in 3.12) - new_box = self._box_config["box_class"](**self.__box_config()) - for x in list(super().keys())[item.start : item.stop : item.step]: - new_box[x] = self[x] - return new_box + keys = list(super().keys())[item] + return self._box_config["box_class"](((key, self[key]) for key in keys), **self.__box_config()) raise BoxTypeError(str(err)) from _exception_cause(err) def __getattr__(self, item): diff --git a/test/test_box_slices.py b/test/test_box_slices.py new file mode 100644 index 0000000..278edc9 --- /dev/null +++ b/test/test_box_slices.py @@ -0,0 +1,83 @@ +"""Slicing creates an independent Box with the source's options.""" + +import sys + +import pytest + +from box import Box, BoxError, ConfigBox + + +@pytest.mark.parametrize("box_class", [Box, ConfigBox]) +@pytest.mark.parametrize("frozen", [False, True]) +@pytest.mark.parametrize("selection", [slice(None), slice(1, 3), slice(None, None, -1), slice(2, 2)]) +def test_slice_preserves_order_and_frozen_state(box_class, frozen, selection): + source = box_class(first=1, nested={"value": 2}, rows=[{"value": 3}], frozen_box=frozen) + expected = list(source.items())[selection] + source_hash = hash(source) if frozen else None + + result = source[selection] + + assert type(result) is box_class + assert list(result.items()) == expected + assert result is not source + if frozen: + with pytest.raises(BoxError, match="frozen"): + result.extra = 4 + if "nested" in result: + with pytest.raises(BoxError, match="frozen"): + result.nested.value = 4 + if "rows" in result: + with pytest.raises(BoxError, match="frozen"): + result.rows[0].value = 4 + assert isinstance(hash(result), int) + assert hash(source) == source_hash + else: + result.extra = 4 + assert "extra" not in source + assert list(source) == ["first", "nested", "rows"] + + +@pytest.mark.parametrize("frozen", [False, True]) +def test_slice_keeps_explicit_none_with_default_box(frozen): + source = Box([("value", None)], default_box=True, frozen_box=frozen) + + result = source[:] + + assert list(result.items()) == [("value", None)] + assert isinstance(result.missing, Box) + assert list(result) == ["value"] + + +@pytest.mark.parametrize("frozen", [False, True]) +def test_slice_recasts_selected_values_once(frozen): + calls = [] + + def recast(value): + calls.append(value) + return value + "!" + + source = Box(tag="value", omitted=1, frozen_box=frozen, box_recast={"tag": recast}) + calls.clear() + + result = source[:1] + + assert result.tag == "value!!" + assert calls == ["value!"] + assert source.tag == "value!" + + +@pytest.mark.parametrize("frozen", [False, True]) +def test_slice_keeps_dotted_options(frozen): + source = Box(nested={"value": 1}, frozen_box=frozen, box_dots=True) + + result = source[:] + + assert result["nested.value"] == 1 + + +@pytest.mark.skipif(sys.version_info < (3, 12), reason="slice keys require Python 3.12") +def test_stored_slice_key_still_returns_its_value(): + key = slice(0, 1) + source = Box({key: "stored"}, frozen_box=True) + + assert source[key] == "stored"