Skip to content
Open
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
1 change: 1 addition & 0 deletions AUTHORS.rst
Original file line number Diff line number Diff line change
Expand Up @@ -128,3 +128,4 @@ Suggestions and bug reporting:

- Mrunmayee Daware (Mrun25)
- Peter Olkhovets (peterolkhov)
- anticipate218
5 changes: 5 additions & 0 deletions CHANGES.rst
Original file line number Diff line number Diff line change
@@ -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
-------------

Expand Down
12 changes: 4 additions & 8 deletions box/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand All @@ -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):
Expand Down
83 changes: 83 additions & 0 deletions test/test_box_slices.py
Original file line number Diff line number Diff line change
@@ -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"