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
