Python memoryview
memoryview provides a Python-level view of the internal data of an object that supports the buffer protocol (like bytes and bytearray), without copying the data.
Creating a memoryview
Wrap a bytes-like object with memoryview() to access its contents efficiently.
Example
Create a memoryview from bytes and inspect its type:
x = memoryview(bytes(5))
print(x)
print(type(x))
Try it Yourself »
Slicing and modifying via memoryview
When the underlying object is mutable (e.g. bytearray), you can modify the data through the memoryview without copying.
Example
Slice and assign through a memoryview:
b = bytearray(b"abcdef")
v = memoryview(b)
print(v[1:4].tobytes()) # b'bcd'
v[0] = ord('Z') # modify original buffer
print(b) # bytearray(b"Zbcdef")
Try it Yourself »
Converting back
Use .tobytes() or convert to bytes() when you need a copy of the data.
See also
Reference: memoryview()