Skip to content

Commit 33fac2b

Browse files
authored
ByteArray access without item expansion in Part[] (#1509)
Add `__getitem(self, value)` to `ByteArray` so we can access a Python `bytearray` element without expanding the full Python `bytearray` value into a Mathics3 ListExpression. There might be other places in the Mathics3 where we might benefit from this. But this is a start.
1 parent e9114d4 commit 33fac2b

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

mathics/builtin/list/eol.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1188,7 +1188,6 @@ def eval(self, list, i, evaluation):
11881188
indices = i.get_sequence()
11891189
# How to deal with ByteArrays
11901190
if list.get_head() is SymbolByteArray:
1191-
list = list.evaluate(evaluation)
11921191
if len(indices) > 1:
11931192
print(
11941193
"Part::partd1: Depth of object ByteArray[<3>] "
@@ -1200,7 +1199,7 @@ def eval(self, list, i, evaluation):
12001199
idx = idx.value
12011200
if idx == 0:
12021201
return SymbolByteArray
1203-
n = len(list.items)
1202+
n = len(list.value)
12041203
if idx < 0:
12051204
idx = n - idx
12061205
if idx < 0:
@@ -1211,7 +1210,7 @@ def eval(self, list, i, evaluation):
12111210
if idx > n:
12121211
evaluation.message("Part", "partw", i, list)
12131212
return
1214-
return list.items[idx]
1213+
return Integer(list[idx])
12151214
if idx is Symbol("System`All"):
12161215
return list
12171216
# TODO: handling ranges and lists...

mathics/core/atoms.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,12 @@ def __new__(cls, value):
675675
self.hash = hash(("ByteArray", str(self.value)))
676676
return self
677677

678+
def __getitem__(self, index: int) -> int:
679+
"""
680+
Support List index lookup without having to expand the entire bytearray into a Mathics3 list.
681+
"""
682+
return self.value[index]
683+
678684
def __getnewargs__(self):
679685
return (self.value,)
680686

@@ -701,9 +707,9 @@ def default_format(self, evaluation, form) -> str:
701707
return '"' + value.__str__() + '"'
702708

703709
@property
704-
def items(self) -> Tuple[int, ...]:
710+
def items(self) -> Tuple[Integer, ...]:
705711
"""
706-
Return a tuple value of Mathics3 Inteters for each element of the ByteArray.
712+
Return a tuple value of Mathics3 Integers for each element of the ByteArray.
707713
"""
708714
if self._items is None:
709715
self._items = tuple([Integer(i) for i in self.value])

0 commit comments

Comments
 (0)