Memoryview

  • memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.
  • memoryview() takes bytes-like object
  • The memoryview() function allows direct read and write access to an object’s byte-oriented data without needing to copy it first. That can yield large performance gains when operating on large objects since it doesn’t create a copy when slicing
In [27]:
# create a bytearray
byte_array = bytearray('XYZ', 'utf-8')
print(type(byte_array), byte_array) # 'bytearray' bytearray(b'XYZ')

# craete a memoryview of byte_array
v = memoryview(byte_array)
v[2] = 74 # directly change it without copy

print(byte_array) # bytearray(b'XYJ')
print(byte_array.decode('utf-8')) # XYJ
<class 'bytearray'> bytearray(b'XYZ')
bytearray(b'XYJ')
XYJ

Reference