Python memoryview() Function

Python3 内置函数Python3 Built-in Functions


memoryview()It is a built-in function in Python used to create a memory view.

memoryview returns a "memory view" object, which allows Python code to access the internal data buffer of an object without copying the data. This can improve performance when handling large binary data.

Word Definition: memoryviewIt means "memory view", which is an object that accesses a data buffer.


Basic Syntax and Parameters

Syntax Format

memoryview(obj)

Parameter Description

  • Parameter obj:
    • Type: An object that implements the buffer protocol (such as bytes, bytearray)
    • Description: The object for which to create a memory view.

Function Description

  • Return Value: Returns a memoryview object.
  • Features: Allows direct access to the data inside the object without copying.

Examples

Example 1: Creating a memoryview

Example

# Create from bytearray
data = bytearray(b"Hello")
m = memoryview(data)
print(m)          # Output: <memory at 0x...>

# Create from bytes
data = b"World"
m = memoryview(data)
print(m[0])       # Output: 87 (ASCII code of W)

# Access multiple bytes
print(m[0:3])     # Output: <memory at 0x...>

Expected Output:

<memory at 0x104174c40>
87
<memory at 0x104174c40>

Code Explanation:

  1. memoryview can be created from bytes or bytearray.
  2. It supports indexing and slicing operations.

Example 2: Modifying Data (Mutable Objects Only)

Example

# memoryview can directly modify the underlying data
data = bytearray(b"Hello")
m = memoryview(data)

# Modify the underlying data
m[0] = 74  # 'J'
print(data)  # Output: bytearray(b'Jello')

# Modify by slicing
m[1:5] = b"abcd"
print(data)  # Output: bytearray(b'Jabcd')

# C type format
data = b"\x01\x02\x03\x04"
m = memoryview(data)
print(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 when processing large binary data.


Python3 内置函数Python3 Built-in Functions


Other Extensions