ML Foundations

Use NumPy asarray copy=False only when copying must fail

In NumPy 2.x, asarray(copy=False) is a strict no-copy contract: it raises when conversion needs new storage. Use copy=None when a copy is acceptable.

Example results for Use NumPy asarray copy=False only when copying must fail. same dtype reuses input: True
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Treat copy=False as a requirement, not a preference

When code accepts a Python list or an array from another step, it is tempting to ask NumPy for an array while forbidding an allocation. In NumPy 2.0 and later, `np.asarray(value, copy=False)` means that NumPy must not copy the data. If it cannot produce the requested array without a copy, it raises `ValueError`; it does not quietly allocate and merely try to avoid copying. The `copy` parameter was added in NumPy 2.0. [1]

Use that strict form when a new allocation would violate a memory or ownership contract and rejection is the right outcome. If either reusing storage or making a copy is acceptable, leave the default `copy=None` or specify it. NumPy then copies only when needed for the input representation, dtype, or other requested requirements. This distinction makes the caller's intent explicit instead of relying on an implicit conversion. [1]

References: [1]

Compare an already compatible array with conversions

The example begins with an `int64` ndarray and asks `asarray` for the same representation with `copy=False`. That request succeeds and returns the same object. A second request with the same dtype also succeeds. The identity output is a concrete demonstration for this particular input; it is not a promise that every array-like object or every dtype and memory order can be reused. NumPy documents that a matching ndarray can be returned without a copy. [1]

The next call changes the dtype to `float64` while using `copy=None`, so conversion is permitted and the result has the requested dtype. A Python list also needs to be represented as ndarray storage, so the default-compatible `copy=None` form accepts it. The example then repeats that list conversion with `copy=False` and expects `ValueError`. Those cases show how to choose between an allowed conversion and a required no-copy contract, rather than measuring allocation speed or memory usage. [1, 2]

Executed with Python 3.12.14 and NumPy 2.3.5 on CPU; assertions passed.

"""Show the strict no-copy contract of numpy.asarray in NumPy 2.x."""
import numpy as np

source = np.arange(4, dtype=np.int64)
shared = np.asarray(source, copy=False)
compatible_dtype = np.asarray(source, dtype=np.int64, copy=False)
converted_dtype = np.asarray(source, dtype=np.float64, copy=None)
from_list = np.asarray([4, 5, 6], dtype=np.int64, copy=None)

print("same dtype reuses input:", shared is source)
print("matching dtype reuses input:", compatible_dtype is source)
print("dtype conversion result:", converted_dtype.dtype)
print("list conversion:", from_list.tolist())
try:
    np.asarray([4, 5, 6], dtype=np.int64, copy=False)
except ValueError:
    print("list with copy=False: rejected")
else:
    raise AssertionError("copy=False should reject a list conversion that requires storage")

assert shared is source
assert compatible_dtype is source
assert converted_dtype.dtype == np.dtype(np.float64)
assert from_list.tolist() == [4, 5, 6]

Recorded output

same dtype reuses input: True
matching dtype reuses input: True
dtype conversion result: float64
list conversion: [4, 5, 6]
list with copy=False: rejected

References: [1], [2]

Choose the contract that matches the caller

Prefer `copy=False` when copying must be rejected, and handle the resulting `ValueError` at a boundary where an incompatible input can be reported or routed elsewhere. Prefer `copy=None` when converting a list, changing dtype, or normalizing an input is allowed to allocate. If you need an independent result regardless of compatibility, request `copy=True`; NumPy documents that this always copies the object. [1, 2]

This is a small CPU demonstration on NumPy 2.3.5. It does not quantify allocation cost, guarantee behavior for custom array protocols, or cover device-specific array libraries. Since `copy` on `asarray` is new in NumPy 2.0, older NumPy installations do not provide the same parameter contract. Check the installed version when supporting environments that predate NumPy 2.0. [1]

References: [1], [2]

Sources

  1. NumPy: asarray
  2. NumPy: array