MCPcopy Create free account
hub / github.com/cdgriffith/Box / BoxList

Class BoxList

box/box_list.py:42–838  ·  view source on GitHub ↗

Drop in replacement of list, that converts added objects to Box or BoxList objects as necessary.

Source from the content-addressed store, hash-verified

40
41
42class BoxList(list):
43 """
44 Drop in replacement of list, that converts added objects to Box or BoxList
45 objects as necessary.
46 """
47
48 def __new__(cls, *args, **kwargs):
49 obj = super().__new__(cls, *args, **kwargs)
50 # This is required for pickling to work correctly
51 obj.box_options = {"box_class": box.Box}
52 obj.box_options.update(kwargs)
53 obj.box_org_ref = None
54 return obj
55
56 def __init__(self, iterable: Iterable | None = None, box_class: type[box.Box] = box.Box, **box_options):
57 values = iterable
58 if self:
59 values = list(iterable) if iterable is not None else []
60 super().clear()
61 if iterable is not self:
62 self.__dict__.pop("_box_comments", None)
63 self.__dict__.pop("_box_comments_document", None)
64 self.box_options = box_options
65 self.box_options["box_class"] = box_class
66 self.box_org_ref = iterable
67 # 2026-10-10: Iteration does not require a truth value.
68 if iterable is not None:
69 for x in values:
70 list.append(self, self._convert(x))
71 if isinstance(iterable, BoxList) and iterable is not self:
72 iterable._comment_copy_to(self)
73 self.box_org_ref = None
74
75 def __getitem__(self, item, _ignore_default=False):
76 if self.box_options.get("box_dots") and isinstance(item, str) and item.startswith("["):
77 list_pos = _list_pos_re.match(item)
78 if list_pos is None:
79 raise BoxTypeError(f"Invalid list index: {item!r}")
80 value = super().__getitem__(int(list_pos.groups()[0]))
81 if len(list_pos.group()) == len(item):
82 return value
83 children = item[len(list_pos.group()) :].lstrip(".")
84 if _ignore_default and isinstance(value, (box.Box, BoxList)):
85 return value.__getitem__(children, _ignore_default=True)
86 return value.__getitem__(children)
87 if isinstance(item, tuple):
88 result = self
89 for idx in item:
90 if isinstance(result, list):
91 result = result[idx]
92 else:
93 raise BoxTypeError(f"Cannot numpy-style indexing on {type(result).__name__}.")
94 return result
95 return super().__getitem__(item)
96
97 def __delitem__(self, key):
98 if self.box_options.get("frozen_box"):
99 raise BoxError("BoxList is frozen")

Calls

no outgoing calls