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

Class _BoxTuple

box/box.py:92–156  ·  view source on GitHub ↗

The tuple ``frozen_box`` stores a list as. Unlike a plain tuple it can carry comments (#184) and follows ``box_dots`` list paths such as ``"[0].key"``.

Source from the content-addressed store, hash-verified

90
91
92class _BoxTuple(tuple):
93 """
94 The tuple ``frozen_box`` stores a list as. Unlike a plain tuple it can carry comments (#184) and
95 follows ``box_dots`` list paths such as ``"[0].key"``.
96 """
97
98 def __getitem__(self, item, _ignore_default=False):
99 if isinstance(item, str) and item.startswith("["):
100 list_pos = _tuple_pos_re.match(item)
101 if list_pos is None:
102 raise BoxTypeError(f"Invalid list index: {item!r}")
103 value = tuple.__getitem__(self, int(list_pos.group(1)))
104 children = item[list_pos.end() :].lstrip(".")
105 if not children:
106 return value
107 if _ignore_default and isinstance(value, (Box, box.BoxList, _BoxTuple)):
108 return value.__getitem__(children, _ignore_default=True)
109 return value[children]
110 return tuple.__getitem__(self, item)
111
112 def _comment_store(self, create: bool = True) -> Any:
113 store = self.__dict__.get("_box_comments")
114 if store is None and create:
115 store = self.__dict__["_box_comments"] = {}
116 return store
117
118 def _comment_document(self, create: bool = True) -> Any:
119 document = self.__dict__.get("_box_comments_document")
120 if document is None and create:
121 document = self.__dict__["_box_comments_document"] = {}
122 return document
123
124 def _comment_check_frozen(self):
125 raise BoxError("Box is frozen")
126
127 def _comment_owner(self, key):
128 if key is None:
129 return self, None
130 if isinstance(key, int) and not isinstance(key, bool):
131 index = key + len(self) if key < 0 else key
132 if 0 <= index < len(self):
133 return self, index
134 elif isinstance(key, str) and key.startswith("["):
135 list_pos = _tuple_comment_index_re.match(key)
136 if list_pos is not None:
137 index = int(list_pos.group(1))
138 index = index + len(self) if index < 0 else index
139 rest = key[list_pos.end() :].lstrip(".")
140 if 0 <= index < len(self):
141 if not rest:
142 return self, index
143 child = tuple.__getitem__(self, index)
144 if hasattr(child, "_comment_owner"):
145 return child._comment_owner(rest)
146 raise BoxKeyError(f"{key!r} is not in the frozen list, comments can only be attached to existing items")
147
148 def get_comment(self, key: Any = None) -> dict | None:
149 """The comments of an item (see ``BoxList.get_comment``), ``None`` for the document comments."""

Callers 1

_recursive_tuplesFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected