← index #1710PR #1374
Related · medium · value 1.372
QUERY · ISSUE

bytearray slice assignment fails for derived types

openby mbueschopened 2015-12-11updated 2024-08-28
docs

The type check for slice assignment to bytearray derived types seems to be a bit too strict:

class MyBytearray(bytearray): pass

a = MyBytearray(4)
b = MyBytearray(4)
a[0:4] = b

results in this error:

Traceback (most recent call last):
  File "test.py", line 5, in <module>
NotImplementedError: array/bytes required on right side
CANDIDATE · PULL REQUEST

memoryview: slice assignment RFC

closedby dxxbopened 2015-07-11updated 2015-07-20

Hi,

I'd like to copy memoryview slices without resorting to copying byte by byte and found that things like memview2[1:3] = memview1[0:2] do not currently work so I took a stab at adding support for it. Before applying the PR, the augmented memoryview test below results in the following output:

# ../unix/micropython basics/memoryview1.py
4
49 50 52
[49, 50, 51, 52]
TypeError
bytearray(b'\x01234')
[1, 50, 51, 52]
[50, 51, 52]
[50, 51]
bytearray(b'\x00\x00')
[1, 2, 3, 4]
[2, 3]
array('i', [1, 2, 6, 4])
array/bytes required on right side
array/bytes required on right side
lhs and rhs should be compatible
lhs and rhs should be compatible
array/bytes required on right side

Applying the PR I get:

# ../unix/micropython basics/memoryview1.py
4
49 50 52
[49, 50, 51, 52]
TypeError
bytearray(b'\x01234')
[1, 50, 51, 52]
[50, 51, 52]
[50, 51]
bytearray(b'\x00\x00')
[1, 2, 3, 4]
[2, 3]
array('i', [1, 2, 6, 4])
bytearray(b'5128')
bytearray(b'5128')
bytearray(b'1212')
ValueError
ValueError

For reference Python3.4 output matches:

# python3.4 basics/memoryview1.py                                                                                                                             
4
49 50 52
[49, 50, 51, 52]
TypeError
bytearray(b'\x01234')
[1, 50, 51, 52]
[50, 51, 52]
[50, 51]
bytearray(b'\x00\x00')
[1, 2, 3, 4]
[2, 3]
array('i', [1, 2, 6, 4])
bytearray(b'5128')
bytearray(b'5128')
bytearray(b'1212')
ValueError
ValueError

Comments?

Keyboard

j / / n
next pair
k / / p
previous pair
1 / / h
show query pane
2 / / l
show candidate pane
c
copy suggested comment
r
toggle reasoning
g i
go to index
?
show this help
esc
close overlays

press ? or esc to close

copied