Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use memoryview on Python 3 strings?

In Python 3, executing:

memoryview("this is a string")

produces the error:

TypeError: memoryview: str object does not have the buffer interface

What should I do in order to make memoryview accept strings or what transformation should I do to my strings in order to be accepted by memoryview?

like image 901
pgmank Avatar asked Apr 27 '26 16:04

pgmank


1 Answers

From the docs, memoryview works only over objects which support the bytes or bytearray interface. (These are similar types except the former is read-only.)

Strings in Python 3 are not raw byte buffers we can directly manipulate, rather they are immutable sequences of Unicode runes or characters. A str can be converted to a buffer, though, by encoding it with any of the supported string encodings like 'utf-8', 'ascii', etc.

memoryview(bytes("This is a string", encoding='utf-8'))

Note that the bytes() call necessarily involves converting and copying the string data into a new buffer accessible to memoryview. As should be evident from the preceding paragraph, is not possible to directly create a memoryview over the str's data.

like image 188
Cameron Flint Avatar answered Apr 29 '26 14:04

Cameron Flint