Memory Views

Python AdvancedMemoryFree Lesson

Advertisement

Introduction

Memoryview provides a view into a mutable buffer without copying data. It enables efficient slicing and type-casting of binary data.

Basic memoryview

# Create bytes-like object
data = bytearray(b"Hello World")

# Create memory view
mv = memoryview(data)

print(mv[0])        # 72 (ASCII 'H')
print(mv[0:5])      # memoryview of 'Hello'
print(bytes(mv[6:]))  # b'World'

# Modify through view
mv[0] = ord('J')
print(bytes(data))  # b"Jello World"

Slice Assignment

data = bytearray(10)
mv = memoryview(data)

# Assign single byte
mv[0] = 65

# Assign slice
mv[1:4] = b"ABC"

# Assign with different length (must match)
mv[5:8] = bytes([1, 2, 3])

print(bytes(data))  # b'ABC\x00\x01\x02\x03\x00'

Casting to Different Types

import struct

data = struct.pack("4I", 1, 2, 3, 4)
mv = memoryview(data)

# Cast to unsigned integers
int_view = mv.cast("I")
print(list(int_view))  # [1, 2, 3, 4]

# Cast to bytes
bytes_view = mv.cast("B")
print(list(bytes_view))  # [1, 0, 0, 0, 2, 0, 0, 0, ...]

Tobytes and Tolist

data = bytearray([1, 2, 3, 4, 5])
mv = memoryview(data)

# Convert to bytes (copy)
copy = mv.tobytes()
print(copy)  # b'\x01\x02\x03\x04\x05'

# Convert to list
lst = mv.tolist()
print(lst)  # [1, 2, 3, 4, 5]

# Convert to readonly
readonly = mv.toreadonly()

Use with NumPy

import numpy as np

# NumPy array to memoryview
arr = np.array([1, 2, 3, 4, 5], dtype=np.int32)
mv = memoryview(arr)

print(mv[0])  # 1
print(mv.shape)  # (5,)

# Modify through memoryview
mv[0] = 10
print(arr[0])  # 10

Practice Problems

  1. Create memoryview from bytearray
  2. Modify data through memoryview
  3. Cast to different types
  4. Use slice assignment
  5. Share memory with NumPy

Advertisement

Need Expert Python Help?

Get personalized tutoring, project support, or professional consulting.

Advertisement