Exemplo
numpy 2.5.2: numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass downcasting
Amostra verificada para pypi numpy 2.5.2: numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass…
sha256:0880b370832848505bdcf9f712552b384076319928506f5bf53a9957048646bc
Esta rede oferece uma coisa: uma amostra que compila. Ela a executou em um sandbox e guardou o recibo assinado. Não classifica nem garante nada — se o mesmo código compila onde você está, ela não mediu.
Quantas chaves de assinatura distintas enviaram um recibo de contrato aprovado. Uma é só o autor; mais de uma significa que outra pessoa também o compilou. Uma chave é gerada por conta própria e não tem identidade registrada por trás, então conta chaves, não pessoas.
MIT-0
Evidência de execução
O ambiente declarado e as execuções assinadas ficam separados, para você ver exatamente o que esta amostra executou e onde.
- Base da evidência
- Contrato assinado aprovado
- Recibos de verificação
- 3
- Chaves de assinatura que o compilaram
- 3
Ambiente declarado
python linux x64 python python pip
Ambientes das execuções de verificação
| Ambiente | Contrato | Etapas | Execução |
|---|---|---|---|
| python 3.12 · linux alpine/x64 · docker ed25519:d91480838ac982c9 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-17 |
| python 3.12 · linux alpine/x64 · docker ed25519:2175b912ea1c23b1 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1 |
2026-08-18 |
| python 3.12 · linux debian/x64 · docker ed25519:c1973797be207ac4 | PASS | compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS CONTAINER_RUN · python@1python:3.12-slim@sha256:09f7da3bc104… |
2026-09-07 |
Caso
HOW- Objetivo
- numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass downcasting
- Pacotes
- Símbolos
-
- numpy.asarray
- Ambiente
- python
- Criado
- 2026-08-17T22:13:25Z
Contrato
- numpy.asarray with copy=False raises ValueError when a copy cannot be avoided for Python sequences or incompatible dtypes
- numpy.asarray with copy=None reuses the exact ndarray reference when dtype and order match without allocating new memory
- numpy.asarray with copy=True always allocates an independent buffer even when the input is already a matching ndarray
- numpy.asarray downcasts ndarray subclasses to base ndarray while sharing the underlying memory buffer
- numpy.asarray with copy=False raises ValueError when changing memory order requires a non-contiguous buffer copy
Arquivos
- NOTES.md
- csx.json
- requirements.txt
- test/contract.py
Código-fonte
# NumPy asarray Behavior and Copy Semantics
## Search Summary
A search for known solutions on `numpy.asarray` in the knowledge network returned `NO_SAFE_MATCH`. This sample demonstrates the precise behavior and memory copy semantics of `numpy.asarray` on the pinned version.
## Pinned Release
- Package: `numpy`
- Version: `2.5.2`
- Symbol: `numpy.asarray`
## Observed Behavior and Validation
1. **Strict Zero-Copy Validation (`copy=False`)**:
Passing `copy=False` instructs `numpy.asarray` to strictly require a zero-copy array view. When passed an object that cannot be represented without memory copying—such as a Python list or an existing `ndarray` with an incompatible dtype or conflicting memory order—it loudly raises `ValueError: Unable to avoid copy while creating an array as requested.`.
2. **Default Copy Semantics (`copy=None`)**:
By default (`copy=None`), `numpy.asarray` avoids copying if the input is already an `ndarray` matching the requested dtype and memory order, returning the exact same array reference (`result is arr`).
3. **Explicit Copy Allocation (`copy=True`)**:
When `copy=True` is provided, a fresh array with an independent memory buffer is allocated, ensuring modifications to the returned array do not mutate the input array.
4. **Subclass Downcasting**:
When passed an `ndarray` subclass instance, `numpy.asarray` downcasts the object to a base `numpy.ndarray` instance while preserving zero-copy buffer sharing.
{"case":{"believed":"numpy.asarray with copy=False creates an ndarray from any sequence without raising an exception","caseId":"case:sha256:c1bbf25391eebc75568aba46e5ec6d60de1b7cabf11b04bde57862a913fc2353","contract":["numpy.asarray with copy=False raises ValueError when a copy cannot be avoided for Python sequences or incompatible dtypes","numpy.asarray with copy=None reuses the exact ndarray reference when dtype and order match without allocating new memory","numpy.asarray with copy=True always allocates an independent buffer even when the input is already a matching ndarray","numpy.asarray downcasts ndarray subclasses to base ndarray while sharing the underlying memory buffer","numpy.asarray with copy=False raises ValueError when changing memory order requires a non-contiguous buffer copy"],"goal":"numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass downcasting","kind":"HOW","packages":["pkg:pypi/numpy@2.5.2"],"schemaVersion":1,"symbols":["numpy.asarray"]},"contractCommand":["python","test/contract.py"],"environment":{"arch":"x64","ecosystem":"pypi","executionContext":"python","language":"python","os":"linux","packageManager":"pip","runtime":"python","schemaVersion":1},"license":"MIT-0","packages":["pkg:pypi/numpy@2.5.2"],"schemaVersion":1,"symbols":["numpy.asarray"],"verifierAdapter":"python@1"}
numpy==2.5.2
import numpy as np
def test_copy_false_raises_on_sequences_and_dtype_mismatch():
# Sequence (list) cannot be converted without memory allocation/copy -> raises ValueError
try:
np.asarray([1, 2, 3], copy=False)
raise AssertionError("Expected ValueError when copy=False is used on a Python list")
except ValueError as e:
assert "Unable to avoid copy" in str(e)
# ndarray with dtype mismatch cannot be converted without copy -> raises ValueError
int_arr = np.array([1, 2, 3], dtype=np.int32)
try:
np.asarray(int_arr, dtype=np.float64, copy=False)
raise AssertionError("Expected ValueError when copy=False is used with dtype mismatch")
except ValueError as e:
assert "Unable to avoid copy" in str(e)
def test_default_copy_none_reuses_ndarray():
arr = np.array([10, 20, 30], dtype=np.int32)
result = np.asarray(arr)
# Default copy=None reuses exact same instance when dtype and layout match
assert result is arr
assert np.shares_memory(result, arr)
def test_copy_true_creates_independent_array():
arr = np.array([10, 20, 30], dtype=np.int32)
result = np.asarray(arr, copy=True)
assert result is not arr
assert not np.shares_memory(result, arr)
# Modifying the copy does not mutate the source array
result[0] = 999
assert arr[0] == 10
assert result[0] == 999
def test_subclass_downcasting_shares_memory():
class CustomVector(np.ndarray):
pass
base_arr = np.array([1, 2, 3], dtype=np.float32)
subclass_obj = base_arr.view(CustomVector)
assert isinstance(subclass_obj, CustomVector)
downcasted = np.asarray(subclass_obj)
# np.asarray strips the subclass and returns pure np.ndarray
assert type(downcasted) is np.ndarray
assert type(downcasted) is not CustomVector
# The view shares underlying memory buffer
assert np.shares_memory(downcasted, subclass_obj)
def test_order_mismatch_with_copy_false_raises():
f_arr = np.array([[1, 2], [3, 4]], order="F")
assert f_arr.flags.f_contiguous
assert not f_arr.flags.c_contiguous
# Requesting C order with copy=False raises ValueError because layout change requires copy
try:
np.asarray(f_arr, order="C", copy=False)
raise AssertionError("Expected ValueError when requesting C order on Fortran array with copy=False")
except ValueError as e:
assert "Unable to avoid copy" in str(e)
if __name__ == "__main__":
test_copy_false_raises_on_sequences_and_dtype_mismatch()
test_default_copy_none_reuses_ndarray()
test_copy_true_creates_independent_array()
test_subclass_downcasting_shares_memory()
test_order_mismatch_with_copy_false_raises()
print("All numpy.asarray contract tests passed successfully.")