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

Class BoxList

box/box_list.py:42–821  ·  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 self.box_options = box_options
58 self.box_options["box_class"] = box_class
59 self.box_org_ref = iterable
60 # 2026-10-10: Iteration does not require a truth value.
61 if iterable is not None:
62 for x in iterable:
63 list.append(self, self._convert(x))
64 if isinstance(iterable, BoxList) and iterable is not self:
65 iterable._comment_copy_to(self)
66 self.box_org_ref = None
67
68 def __getitem__(self, item, _ignore_default=False):
69 if self.box_options.get("box_dots") and isinstance(item, str) and item.startswith("["):
70 list_pos = _list_pos_re.match(item)
71 if list_pos is None:
72 raise BoxTypeError(f"Invalid list index: {item!r}")
73 value = super().__getitem__(int(list_pos.groups()[0]))
74 if len(list_pos.group()) == len(item):
75 return value
76 children = item[len(list_pos.group()) :].lstrip(".")
77 if _ignore_default and isinstance(value, (box.Box, BoxList)):
78 return value.__getitem__(children, _ignore_default=True)
79 return value.__getitem__(children)
80 if isinstance(item, tuple):
81 result = self
82 for idx in item:
83 if isinstance(result, list):
84 result = result[idx]
85 else:
86 raise BoxTypeError(f"Cannot numpy-style indexing on {type(result).__name__}.")
87 return result
88 return super().__getitem__(item)
89
90 def __delitem__(self, key):
91 if self.box_options.get("frozen_box"):
92 raise BoxError("BoxList is frozen")
93 if self.box_options.get("box_dots") and isinstance(key, str) and key.startswith("["):
94 list_pos = _list_pos_re.match(key)
95 if list_pos is None:
96 raise BoxTypeError(f"Invalid list index: {key!r}")
97 pos = int(list_pos.groups()[0])
98 if len(list_pos.group()) == len(key):
99 return self.__delitem__(pos)

Calls

no outgoing calls