CodeSampleX

Ejemplo

numpy 2.5.2: numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass downcasting

Muestra 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 red ofrece una sola cosa: una muestra que compila. La ejecutó en un sandbox y guardó el recibo firmado. No califica ni garantiza nada: si el mismo código compila donde estás no es algo que haya medido. Cuántas claves de firma distintas presentaron un recibo de contrato aprobado. Una es solo el autor; más de una significa que alguien más también lo compiló. Una clave se genera sola y no tiene identidad registrada detrás, así que cuenta claves, no personas. MIT-0

Evidencia de ejecución

El entorno declarado y las ejecuciones firmadas se muestran por separado, para que veas exactamente qué ejecutó esta muestra y dónde.

Base de evidencia
Contrato firmado aprobado
Recibos de verificación
3
Claves de firma que lo compilaron
3
Entorno declarado python linux x64 python python pip

Entornos de las ejecuciones de verificación

Entorno Contrato Etapas Ejecución
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
Paquetes
Símbolos
  • numpy.asarray
Entorno
python
Creado
2026-08-17T22:13:25Z

Contrato

  1. numpy.asarray with copy=False raises ValueError when a copy cannot be avoided for Python sequences or incompatible dtypes
  2. numpy.asarray with copy=None reuses the exact ndarray reference when dtype and order match without allocating new memory
  3. numpy.asarray with copy=True always allocates an independent buffer even when the input is already a matching ndarray
  4. numpy.asarray downcasts ndarray subclasses to base ndarray while sharing the underlying memory buffer
  5. numpy.asarray with copy=False raises ValueError when changing memory order requires a non-contiguous buffer copy

Archivos

  • NOTES.md
  • csx.json
  • requirements.txt
  • test/contract.py

Descargar el artefacto de código fuente (tar.gz)

Código fuente

NOTES.md
# 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.
csx.json
{"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"}
requirements.txt
numpy==2.5.2
test/contract.py
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.")

Seeder de origen

csx-seed