liveBook · Manning

Np.shares_memory

As explained in Fast Python: High performance techniques for large datasets

np.shares_memory is a NumPy function that determines whether two arrays share memory.

np.shares_memory determines whether two NumPy arrays overlap in memory. It tests memory sharing directly, which is more general than checking whether one array is a view of the other. section 4.1.1

A shared base usually implies shared memory, but the reverse is not guaranteed: memory can be shared without the arrays having the same base. Copies do not share the original array’s data. section 4.1.1

Use the result to distinguish common array transformations:

  • A view created with np.flipud(image_arr) shares memory with image_arr. section 4.1.1
  • A copied result created with np.flipud(image_arr).copy() does not share memory with image_arr. section 4.1.1
  • Reshaping and transposing can produce differently shaped arrays that still share the same raw data. section 4.1.2
  • Advanced indexing can produce an array that does not share memory with the indexed matrix. section 4.1.2

Check a view against a copy

image_arr = np.array(image) flipped_from_view = np.flipud(image_arr) flipped_from_copy = np.flipud(image_arr).copy() np.shares_memory(image_arr, flipped_from_copy) # False np.shares_memory(image_arr, flipped_from_view) # True section 4.1.1

The test can be computationally nontrivial for complex array layouts. When an exact determination is impractical, np.may_share_memory offers a faster guess instead. section 4.1.1

print(np.shares_memory(image_arr, flipped_from_copy),
      np.shares_memory(image_arr, flipped_from_view))

Run the direct comparison that reports whether an image array shares memory with copied and view-based flips. section 4.1.1

How Fast Python: High performance techniques for large datasets covers it

How deep it goes
Explains exact sharing, base relationships, and difficult layouts, while deferring detailed allocation machinery.
Examples
Uses flipped image arrays, reshaped and transposed matrices, reversed slices, strided slices, and advanced indexing.
What it assumes
Recognizes NumPy arrays and basic slicing, while introducing views, copies, raw data, and strides.
What you can do after
Diagnose/debug with it: verify whether derived arrays can affect one another through shared storage.
How it connects
Connects memory sharing with NumPy views, copies, memoryviews, strides, reshaping, transposition, and advanced indexing.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast Python: High performance techniques for large datasets. The section links point to the parts of the book it draws on.