Python memoryview() Function

Returns a memory view of an object.

Syntax

Python
memoryview(object)

Parameters

ParameterDescription
object Required. The object for which the memoryview will be created.

A memoryview allows Python code to access the internal data of an object without copying the data first, which can be a significant performance improvement. Working on binary data in a large image is a good example, where we don't want to create a copy of the entire image to manipulate its pixels. The object must support the buffer protocol.

Built-in objects that support the buffer protocol include bytes and bytearray. Other objects that support the buffer protocol include the Python Image Library (PIL), NumPy arrays, SQLlite databases.

Example

Python
myByteArray = bytearray('ABC', 'utf-8')
view = memoryview(myByteArray)
print(myByteArray)
view[0] = 97 # lowercase a
view[1] = 98 # lowercase b
view[2] = 99 # lowercase c
print(myByteArray)

Output

bytearray(b'ABC')
bytearray(b'abc')