Python memoryview() is a built-in function that returns a “memory view” object created from the given argument.

python memoryview() function

Memory view is a safe way to expose the buffer protocol in Python. Behind the scenes, memoryview() uses buffer protocol to avoid copies. So, let’s learn about buffer protocol first.

What is buffer protocol in Python?

In simple words, a memory array is termed as the buffer and buffer protocol provides a way to access internal data of an object.

Buffer protocol is only accessible to us at the C-API level and not using our normal code base.

Why do we need buffer protocol?

Python creates an intermediate copy of an object when using that object in different operations. This becomes hectic when dealing with huge chunks of data because making a copy of such data will increase the execution time and usage of memory.

So for efficient performance buffer protocol is used which allows one object to expose its internal data (buffers) and the other to access those buffers without intermediate copying.

Use of memory views

Since buffer protocol is only accessible to us at the C-API level and not using our normal code base, memory views are present in Python to expose the same protocol to normal Python code base.

Memoryview objects allow Python code to access the internal data of an object that supports the buffer protocol without copying.

Python memoryview() function allows direct read and write access to an object’s byte-oriented data avoiding the need of copying first. This yields effective performance when operating on large objects since it doesn’t create a copy when slicing.

Python memoryview() Syntax

memoryview(obj)

Python memoryview() takes only one parameter as an argument.

  • obj (required) – object supporting buffer protocol whose internal data is to be exposed – str and bytearray (but not Unicode)

Python memoryview() Example

>>> #creating a memory view
>>> obj = bytearray('Python','utf-8')
>>> m = memoryview(obj)

>>> m[1]
121

>>> #byte from memory view
>>> bytes(m[0:3])
b'Pyt'

>>> #modifying internal data of object using memory view
>>> print('Before updating:', obj)
Before updating: bytearray(b'Python')

>>> #modifying 0th index element using ascii value 90(Z)
>>> m[0] = 90
>>> print('After updating:', obj)
After updating: bytearray(b'Zython')

Here in program we have created a memory view m from byte array object obj and then we accessed zeroth index element which return the corresponding ascii value of the character.

We have also accessed the 3 elements of index 0,1 and 2 and then converted the stream to bytes.

In the last part of the program, we have demonstrated the modification of the memory view’s 0th index to ASCII value as 90 (Z). In this memory view object m references the same buffer or memory and updating the index in m and it also updates obj.