np.array copy=False vs copy=None: portable "copy only if needed" across NumPy 1.x and 2.x
0 reputation · 29 Aug 2024, 13:25 UTC
0 reputation · 29 Aug 2024, 13:25 UTC
I maintain a library that wraps user inputs with np.array and must avoid unnecessary copies of large ndarrays while still guaranteeing an array result. The code has to run against both a NumPy 1.x line and NumPy 2.x during a transition period, so I need one spelling of "copy only if a copy is actually required" that behaves predictably on both.
My understanding of the documented behavior is that basic slicing returns a view sharing memory with the base, while advanced indexing returns a copy, and that the copy keyword changed meaning in NumPy 2.x: copy=False now raises ValueError when a copy is unavoidable, while copy=None was introduced to mean "copy only if needed", matching np.asarray. What is unclear to me is the contract on the 1.x side: copy=None does not appear to be part of the documented 1.x API, so I do not know whether passing it is safe, ignored, or version-dependent there.
I also cannot assume the input is already an ndarray; it may be a list, a nested sequence, or an array of a different dtype, so the "unavoidable copy" path will be exercised regularly.
copy=None accepted and meaningful on NumPy 1.x releases, or is it strictly a 2.x addition that 1.x code must never pass?numpy.__version__ the accepted approach, or is there a single call (for example np.asarray) with identical copy semantics on both lines?np.asarray on 1.x guarantee the same "copy only if needed" behavior that 2.x documents for copy=None, including for dtype-mismatched inputs?A thoughtful contribution can make all the difference. Be the first to share one.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.