Apurva Kunkulol
Apurva Kunkulol

Reputation: 451

Slicing assignment in Memoryview throws a ValueError despite having correct syntax

So I have this code

buffer_size = 190000000
start_offset = 0
b = bytearray(buffer_size)
mv = memoryview(b)
end_offset = len(record)
mv[start_offset: end_offset] = record.encode(constants.file_encoding)

Whenever the last statement is encountered, it throws an error like the following:

ValueError: Memoryview assignment: Lvalue has a different structure than RValue

Upvotes: 4

Views: 1811

Answers (1)

Ry-
Ry-

Reputation: 224942

If record is a string, len(record) is the number of codepoints in the string; you haven’t encoded it to bytes yet. The length of the bytes object is what you need. Also, the assignment end_offset = len(…) only makes sense when start_offset == 0, and there’s no need to create a memoryview to assign to a slice of a bytearray.

buffer_size = 190000000
b = bytearray(buffer_size)
record_bytes = record.encode(constants.file_encoding)
end_offset = len(record_bytes)
b[:end_offset] = record_bytes

Upvotes: 2

Related Questions