I am trying to work with byte buffers in Python. The way I tried to go about it was to start with a zero-filled bytearray:
>>> d=bytearray(3)
>>> d
bytearray(b'\x00\x00\x00')
So far so good. I had tried to use bytes, but the documentation told me these would not be mutable. However, bytearrays should support mutable operations. Let's say I'm building some low-level fixed-sized packet, zero-padded, and I need to set the first bytes for my header. I try, because I'm lazy:
>>> d[0:1] = b'\x01\x01'
>>> d
bytearray(b'\x01\x01\x00\x00')
What gives? I started with a zero-filled bytearray precisely because I needed to keep the size constant. With the slicing I used, the answer doesn't even make sense: at worst, I expected the assignment of the two bytes to occur in both positions [0,1], adding two extra bytes to the total. Adding one extra byte just sounds nonsensical. Anyway...
Now, sure, let me try to assign each byte individually like a proper person...
>>> d[0] = b'\x01'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'bytes' object cannot be interpreted as an integer
I give up. I'm certainly not going to be working in both bytes and integers at the same time to fix this (and why was that not a problem in the previous example?). And I can't find any meaningful resource on the internet on "bytearray assignments" (the closest was a Wikiversity article which had an empty Assignments section).
Is there a sane way to manipulate bytearrays in Python? Thank you!
Python 3.7.6 (tags/v3.7.6:43364a7ae0, Dec 19 2019, 00:42:30) [MSC v.1916 64 bit (AMD64)] on win32
d[0:1] = b'\x01\x01'will always work that way with built-in slicing, silce notation is non inclusive. Bytearrays are mutable, and can re-size. You wantd[0:2] = b'\x01\x01'Note,bytearrayobjects requireintobjects for assignment (regular and slice-based). Because slice-assigning with another bytes objects will produce ints, notelist(b'\x01')d[0] = 1.