Discussion:
[Numpy-discussion] Why does asarray() create an intermediate memoryview?
Alexander Belopolsky
2016-03-27 21:00:51 UTC
Permalink
In the following session a numpy array is created from an stdlib array:

In [1]: import array

In [2]: base = array.array('i', [1, 2])

In [3]: a = np.asarray(base)

In [4]: a.base
Out[4]: <memory at 0x7fb80383e8c8>

In [5]: a.base.obj
Out[5]: array('i', [1, 2])

In [6]: a.base.obj is base
Out[6]: True

Why can't a.base be base? What is the need for the intermediate memoryview
object?
Pauli Virtanen
2016-03-27 22:21:32 UTC
Permalink
Sun, 27 Mar 2016 17:00:51 -0400, Alexander Belopolsky kirjoitti:
[clip]
Post by Alexander Belopolsky
Why can't a.base be base? What is the need for the intermediate
memoryview object?
Implementation detail vs. life cycle management of buffer acquisitions.

The PEP3118 Py_buffer structure representing an acquired buffer is a C
struct that is not safe to copy (!), and needs to sit in an allocated
blob of memory whose life cycle has to be managed. The acquisition also
needs to be released after use.

Python's memoryview object happens to be a convenient way to babysit this.

Rather than adding a new entry to the ArrayObject struct for a potential
acquired buffer and inserting corresponding release calls, I picked a
more localized solution where the acquisition is managed by the
memoryview object rather than ndarray itself, and the life cycle works out
via the pre-existing ndarray.base refcounting.
--
Pauli Virtanen
Loading...