Python’s MemoryView is a built-in class that takes a portion of an array and processes it as a slice. Any change in the slice affects the array.

Travis Oliphant, the author of NumPy, looks at memory views this way: Memory views are really generalized and de-mathematized NumPy arrays. It allows us to share memory between data structures without having to copy content. The data structures can be in any form, such as PIL images, SQLite databases, NumPy arrays, etc. This capability is important for scenarios that deal with large data sets.

PIL: Python Imaging Library is a third party image processing Library for Python.

The memoryView.cast () method can read and write the same block of memory data in different ways, and operate at the byte level.

Luciano Ramalho gives an example of how memoryView can be used to modify exactly one byte of data in an array.

numbers = array.array('h', [-2, -1, 0, 1, 2])
memv = memoryview(numbers)
logging.info('len(memv) -> %s', len(memv))

logging.info('memv[0] -> %s', memv[0])

memv_oct = memv.cast('B')
list = memv_oct.tolist()
logging.info('list -> %s', list)

memv_oct[5] = 4
logging.info('numbers -> %s', numbers)
Copy the code

Running results:

INFO - len(memv) -> 5
INFO - memv[0] -> -2
INFO - list -> [254, 255, 255, 255, 0, 0, 1, 0, 2, 0]
INFO - numbers -> array('h', [-2, -1, 1024, 1, 2])
Copy the code
  1. First, create an array of five short signed integers.
  2. Then create an in-memory view of the array. You can see that it has the same number of elements as the array, and it contains the same elements as the array;
  3. The memory view of this signed integer is then converted to the memory view of unsigned characters. You’ll see that the new memory view becomes an array of 10 elements;
  4. Then in the new memory view, the byte at index position 5 is assigned to 4, that is, the highest byte of the 2-byte integer is changed. The third value in the original array becomes 1024 (256 × 4).