CodeSampleX

샘플

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

검증된 샘플 — pypi numpy 2.5.2: numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass downcasting. python…

sha256:0880b370832848505bdcf9f712552b384076319928506f5bf53a9957048646bc

이 네트워크가 제공하는 것은 하나입니다. 빌드되는 샘플. 샌드박스에서 돌리고 서명된 영수증을 보관합니다. 등급을 매기지 않고 무엇도 보증하지 않습니다 — 같은 코드가 당신 환경에서 빌드되는지는 측정한 적이 없습니다. 통과한 계약 영수증을 낸 서로 다른 서명 키의 수입니다. 하나면 작성자 혼자이고, 둘 이상이면 다른 사람도 빌드했다는 뜻입니다. 키는 스스로 만드는 것이고 뒤에 등록된 신원이 없으므로, 세는 것은 사람이 아니라 키입니다. MIT-0

실행 증거

선언된 환경과 서명된 실행을 분리해 두었습니다. 이 샘플이 무엇을 어디서 실행했는지 그대로 볼 수 있습니다.

증거 기준
서명된 컨트랙트 통과
검증 영수증
3
빌드한 서명 키
3
선언된 환경 python linux x64 python python pip

검증 실행 환경

환경 컨트랙트 단계 실행일
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

케이스

HOW
목표
numpy.asarray copy parameter enforces strict zero-copy validation and controls memory sharing and subclass downcasting
패키지
심벌
  • numpy.asarray
환경
python
생성일
2026-08-17T22:13:25Z

컨트랙트

  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

파일

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

소스 아티팩트 내려받기 (tar.gz)

소스

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.")

오리진 시더

csx-seed