Mixed advanced and basic indexing in NumPy: restructure for views or accept the copy?
0 reputation · 24 May 2025, 06:59 UTC
I'm designing array access patterns for a numerical pipeline on NumPy 2.x and need to decide how to handle mixed indexing, e.g. arr[[0, 2], 1:3], where an integer array is combined with a slice.
My understanding from the documentation is that pure basic slicing always returns a view sharing memory, while any advanced indexing (integer arrays or boolean masks), including mixed cases, always returns a copy. That boundary has been stable since NumPy 1.13, but it creates a real design tension for me.
On one hand, I could restructure the code to use pure slices (or reshape/stride tricks) wherever in-place updates and zero-copy behavior matter. On the other hand, advanced indexing is far more readable, and I could simply accept the copy and its memory cost, verifying behavior with np.shares_memory() during development.
My specific questions:
- For mixed indexing patterns where I need view semantics, is restructuring into pure slices the only safe documented option, or is there a supported alternative short of
as_strided? - Is relying on
np.shares_memory()checks in tests a reasonable guard against silently regressing into copy behavior, or is it considered too fragile? - Given the long-standing upstream debate about views for mixed indexing, is the current copy behavior something I can treat as a guaranteed contract for future NumPy 2.x releases?