Python memoryview() Function
memoryview() is a built-in Python function that creates a memory view.
memoryview returns a "memory view" object that allows Python code to access an object's internal data buffer without copying the data. This can improve performance when handling large binary data.
Word meaning: memoryview means "memory view", an object for accessing data buffers.
Basic syntax and parameters
Syntax format
memoryview(obj)
Parameter Description
- Parameter obj:
- Type: an object implementing the buffer protocol (such as bytes or bytearray)
- Description: the object for which to create a memory view.
Function description
- Return Value: returns a memoryview object.
- Feature: allows direct access to an object's internal data without copying.
Example
Example 1: creating a memoryview
Example
Create from a bytearray
data
=
bytearray
(
b
"Hello"
)
m
=
memoryview
(
data
)
(
m
)
Output:
Create from bytes
data
=
b
"World"
m
=
memoryview
(
data
)
(
m
[
0
]
)
Output: 87 (the ASCII code of W)
Access multiple bytes
(
m
[
0
:
3
]
)
Output:
Expected output:
87
Code analysis:
- A memoryview can be created from bytes or bytearray.
- It supports indexing and slicing.
Example 2: modifying data (mutable objects only)
Example
memoryview can modify the underlying data directly
data
=
bytearray
(
b
"Hello"
)
m
=
memoryview
(
data
)
Modify the underlying data
m
[
0
]
=
74
'J'
(
data
)
Output: bytearray(b'Jello')
Slice modification
m
[
1
:
5
]
=
b
"abcd"
(
data
)
Output: bytearray(b'Jabcd')
C type format
data
=
b
"\x01\x02\x03\x04"
m
=
memoryview
(
data
)
(
m.
tobytes
(
)
)
Output: b'\x01\x02\x03\x04'
Expected output:
bytearray(b'Jello')
bytearray(b'Jabcd')
b'\x01\x02\x03\x04'
memoryview allows direct modification of the underlying data, which is very efficient for handling large binary data.
Python3 built-in function