Interoperability: Protocols and DLPack

This content was generated with the assistance of AI and should be verified against the official documentation before being relied on in production.

This page targets NumPy 2.5 (examples were run on NumPy 2.5.4, pandas 3.1 and array-api-strict 2.6), checked against the official documentation in October 2026. Examples target Python 3.13 or 3.14 and were run on Python 3.13. NumPy is the common currency of the Python data stack: pandas, scikit-learn, SciPy, Matplotlib and most machine-learning libraries read and write ndarrays. This page explains the mechanisms behind that, in three directions, which the official guide also uses to organise the topic:

  • Foreign object to ndarray: how np.asarray(obj) understands an object that is not an array.

  • NumPy function to foreign object: how np.mean(obj) or np.add(obj, 1) can be redirected to another library’s own implementation.

  • Result back to a foreign type: how a subclass or wrapper keeps its type and metadata after a NumPy operation.

A companion page, The Array API Standard, covers the standardised API that sits on top of these protocols.

Converting any object to an ndarray

When a NumPy function such as np.asarray or np.array receives something that is not an ndarray, it tries these mechanisms in a fixed order. The first one that applies wins.

flowchart TD A["np.asarray(obj)"] --> B{"Buffer protocol?"} B -- yes --> Z["ndarray view, no copy"] B -- no --> C{"__array_interface__?"} C -- yes --> Z C -- no --> D{"__array__ method?"} D -- yes --> Y["ndarray from __array__ with dtype and copy"] D -- no --> E["Treat obj as a Python sequence or scalar"]

DLPack is deliberately not part of this chain: NumPy never converts an object through DLPack implicitly, and you must call np.from_dlpack yourself.

The buffer protocol

The Python buffer protocol (PEP 3118) lets an object describe a block of memory: its address, item format, shape and strides. NumPy builds an ndarray that views that memory with no copy. Standard-library bytes, bytearray, array.array and memoryview objects all speak it, as do many extension types (image libraries, Arrow buffers, mmap).

import array
import numpy as np

# Buffer protocol: zero-copy views over bytes-like objects
buf = array.array("d", [1.0, 2.0, 3.0])
view = np.asarray(buf)
view[0] = 99.0
print(buf, view.dtype)

raw = bytearray(8)
arr = np.frombuffer(raw, dtype=np.int16)
arr[0] = 258
print(list(raw), arr.flags.writeable)
ro = np.frombuffer(b"\x01\x00\x02\x00", dtype=np.int16)
print(ro, ro.flags.writeable)

# memoryview is the Python-side name of the buffer protocol
a = np.arange(6, dtype=np.int32).reshape(2, 3)
mv = memoryview(a)
print(mv.shape, mv.strides, mv.format, mv.c_contiguous)

# __array_interface__: a dictionary description of the same information
d = a.__array_interface__
print({k: d[k] for k in ("shape", "typestr", "strides", "version")})

Output:

array('d', [99.0, 2.0, 3.0]) float64
[2, 1, 0, 0, 0, 0, 0, 0] True
[1 2] False
(2, 3) (12, 4) i True
{'shape': (2, 3), 'typestr': '<i4', 'strides': None, 'version': 3}

Three details to notice. Writing through view changed the original array.array, because both share one buffer. np.frombuffer over a mutable bytearray gives a writable array (writing 258 stored the little-endian bytes 2, 1), while over immutable bytes the array is read-only. And strides: None in the interface dictionary means C-contiguous. Memory layout and strides are explained in Memory Layout and Strides, and the view-versus-copy consequences in Copies and Views.

__array_interface__

__array_interface__ is an older protocol that predates the buffer protocol: a dictionary with the shape, typestr, data pointer and optional strides of a block of memory. It is tried second. Libraries that cannot implement the C-level buffer protocol (or need dtype information it cannot express) use it. The dictionary can be attached to any wrapper object, and NumPy will share the memory it points to, so the pointer must stay valid for as long as the array lives. In NumPy 2.5, NumPy scalars export their __array_interface__ directly and read-only, rather than carrying an array copy in a __ref entry, and numpy.ctypeslib.as_ctypes now accepts only an ndarray (convert a scalar with np.asarray first).

__array__ and the copy keyword

__array__ is the fallback for objects that cannot expose memory without work, for example a lazily computed or compressed container. Its signature since NumPy 2.0 is:

def __array__(self, dtype=None, copy=None):
    ...

The copy argument tells the object what it may do:

copy What __array__ must do

None

Copy only if needed, for example because dtype forces a cast.

True

Always return a fresh copy.

False

Raise an exception if a copy would be needed.

If dtype is given and differs from the object’s own, the implementation should cast. NumPy 2.0 changed np.array(obj, copy=False) from "copy only if needed" to "never copy, raise if impossible", so the portable spelling of the old behaviour is np.asarray(obj) or copy=None.

import warnings
import numpy as np


class Celsius:
    """A container that converts itself to an array on demand."""

    def __init__(self, values):
        self._values = [float(v) for v in values]

    def __array__(self, dtype=None, copy=None):
        if copy is False:
            raise ValueError("a copy is always required for this object")
        return np.array(self._values, dtype=dtype)


c = Celsius([20, 25.5, 30])
print(np.asarray(c), np.asarray(c, dtype=np.float32).dtype)
print(np.array(c) + 273.15)
print(np.mean(c))
try:
    np.asarray(c, copy=False)
except ValueError as exc:
    print("ValueError -", exc)


class Old:
    def __array__(self):            # old signature, no dtype or copy
        return np.arange(3)


with warnings.catch_warnings(record=True) as caught:
    warnings.simplefilter("always")
    print(np.array(Old()))
    print(caught[0].category.__name__)

x = np.arange(3)
try:
    np.array(x, dtype=np.float64, copy=False)
except ValueError as exc:
    print("ValueError -", str(exc).splitlines()[0])
print(np.array(x, dtype=np.float64, copy=None).dtype, np.array(x, copy=None) is x, np.asarray(x) is x)

Output:

[20.  25.5 30. ] float32
[293.15 298.65 303.15]
25.166666666666668
ValueError - a copy is always required for this object
[0 1 2]
DeprecationWarning
ValueError - Unable to avoid copy while creating an array as requested.
float64 True True

An __array__ that still has the one-argument signature keeps working, but passing copy=False through np.array raises a DeprecationWarning that tells you to accept dtype and copy. Fix it now: the deprecation is a path to an error. Also remember that converting through __array__ may be slow, may lose metadata (labels, units, masks) and, for objects on a GPU, may transfer data to host memory, so do it explicitly and once.

__numpy_dtype__

Since NumPy 2.4 an object can be used as a dtype by providing a __numpy_dtype__ attribute that returns a real np.dtype. It takes precedence over a plain .dtype attribute, which NumPy also still accepts. The attribute must be a property (or a value), not a method:

import numpy as np


class Meters:
    @property
    def __numpy_dtype__(self):
        return np.dtype(np.float32)


class WithAttr:
    dtype = np.dtype("int16")


print(np.dtype(Meters()), np.dtype(WithAttr()), np.array([1, 2], dtype=Meters()).dtype)

Output:

float32 int16 float32

DLPack

DLPack is a language- and device-neutral description of a tensor in memory, with a small C structure, that lets two libraries exchange an array without a copy. An exporter provides __dlpack__ and __dlpack_device__; the consumer turns it into its own array type. The NumPy entry point is np.from_dlpack(x, /, *, device=None, copy=None), which matches the array API standard (see The Array API Standard).

import numpy as np

x = np.arange(5)
y = np.from_dlpack(x)
print(np.shares_memory(x, y), y.flags.writeable)
x[1] = 100
print(y)                                      # the same memory
print(x.__dlpack_device__())                  # (device type, device id): (1, 0) is the CPU

import array_api_strict as xp                 # pip install array-api-strict

s = xp.arange(5)
n = np.from_dlpack(s)
print(n, np.shares_memory(n, np.asarray(s)))
print(np.from_dlpack(s, copy=True).flags.writeable)
try:
    np.from_dlpack(s, device="cuda")
except ValueError as exc:
    print("ValueError -", exc)
back = xp.from_dlpack(np.arange(3.0))
print(type(back).__name__, back)

Output:

True True
[  0 100   2   3   4]
(1, 0)
[0 1 2 3 4] True
True
ValueError - Device not understood. Only "cpu" is allowed, but received: cuda
Array Array([0., 1., 2.], dtype=array_api_strict.float64)

Points to keep in mind:

  • Explicit only. np.asarray(torch_tensor) goes through __array__, never through DLPack. Call np.from_dlpack when you want the zero-copy device-aware path.

  • CPU only. NumPy has no GPU memory. Importing a tensor that lives on a GPU fails unless you ask for a copy to the CPU with device="cpu" (the library that exports it must support that request, which DLPack version 1 does).

  • Read-only imports. The official guide states that arrays imported through DLPack are read-only for writing or operating in place, and that you should call .copy() to get a writable array at the cost of duplicating memory. In the runs shown above the exporting objects were writable NumPy-family arrays and the imported array reported writeable as True, so check arr.flags.writeable instead of assuming either way.

  • The exporter keeps the memory alive. A view of a producer’s buffer follows the producer’s later writes, as the example with x[1] = 100 shows. Copy if you need a snapshot.

  • Errors. Since NumPy 2.5, np.from_dlpack raises BufferError instead of RuntimeError when the incoming tensor has an unsupported device, dtype or number of dimensions, in line with the DLPack and array API specifications. Catch BufferError in code that must survive older and newer NumPy.

  • Custom dtypes. Authors of user-defined dtypes can register them for DLPack export and import with numpy.dtypes.register_dlpack_dtype (new in 2.5; for dtype authors, to be used with care).

The official guide shows the same mechanism with PyTorch (np.from_dlpack(torch_tensor) is a view; writing to the NumPy side raises ValueError: assignment destination is read-only) and with a CUDA tensor and device="cpu". The guide also reports that exporting a read-only NumPy array to PyTorch fails with a TypeError saying that NumPy currently only supports DLPack for writeable arrays, so keep exported arrays writable.

Operating on foreign objects: __array_ufunc__ and __array_function__

Sometimes you want np.add(obj, 1) or np.mean(obj) to run inside another library, for example on a GPU or lazily, instead of converting to an ndarray first. NumPy supports this through two dispatch protocols.

  • __array_ufunc__(self, ufunc, method, *inputs, **kwargs) (NEP 13) intercepts universal functions: np.add, np.sqrt, the Python operators that map to them, and the ufunc methods (reduce, accumulate, outer, at). The method argument tells you which one was called.

  • __array_function__(self, func, types, args, kwargs) (NEP 18) intercepts every other public NumPy function that can be overridden, such as np.mean, np.concatenate or np.linalg.inv. types is the collection of distinct argument types that implement the protocol.

Both follow the same rule: do the work and return a result, or return NotImplemented to decline. If every candidate declines, NumPy raises TypeError. When several operands define the protocol, subclasses are asked before their superclasses and otherwise operands are asked from left to right.

import numpy as np
from numpy.lib.mixins import NDArrayOperatorsMixin


def unwrap(obj):
    """Replace Labeled objects by their arrays, also inside lists and tuples."""
    if isinstance(obj, Labeled):
        return obj.data
    if isinstance(obj, (list, tuple)):
        return type(obj)(unwrap(item) for item in obj)
    return obj


class Labeled(NDArrayOperatorsMixin):
    """Wraps an array and a label; ufuncs and a few functions keep the label."""

    def __init__(self, data, label):
        self.data = np.asarray(data)
        self.label = label

    def __repr__(self):
        return f"Labeled({self.data!r}, label={self.label!r})"

    def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
        if method != "__call__" or "out" in kwargs:
            return NotImplemented              # let NumPy raise a clear TypeError
        raw = [unwrap(x) for x in inputs]
        return Labeled(ufunc(*raw, **kwargs), self.label)

    def __array_function__(self, func, types, args, kwargs):
        if not all(issubclass(t, Labeled) for t in types):
            return NotImplemented
        result = func(*unwrap(args), **kwargs)
        return Labeled(result, self.label) if isinstance(result, np.ndarray) else result


temps = Labeled([20.0, 25.5, 30.0], "temperature")
print(np.add(temps, 1))
print(1 + temps)                 # operators come from NDArrayOperatorsMixin
print(np.sqrt(temps))
print(np.mean(temps))            # routed through __array_function__
print(np.concatenate([temps, temps]))
try:
    np.add.reduce(temps)         # method is "reduce", not "__call__"
except TypeError as exc:
    print("TypeError -", str(exc)[:58])
try:
    np.add(temps, np.ones(3), out=np.zeros(3))
except TypeError as exc:
    print("TypeError -", str(exc)[:58])

from numpy.testing.overrides import (
    allows_array_function_override,
    allows_array_ufunc_override,
    get_overridable_numpy_array_functions,
)

print(allows_array_ufunc_override(np.add), allows_array_function_override(np.mean))
print(len(get_overridable_numpy_array_functions()) > 100)

Output:

Labeled(array([21. , 26.5, 31. ]), label='temperature')
Labeled(array([21. , 26.5, 31. ]), label='temperature')
Labeled(array([4.47213595, 5.04975247, 5.47722558]), label='temperature')
25.166666666666668
Labeled(array([20. , 25.5, 30. , 20. , 25.5, 30. ]), label='temperature')
TypeError - operand type(s) all returned NotImplemented from __array_u
TypeError - operand type(s) all returned NotImplemented from __array_u
True True
True

What the example shows:

  • NDArrayOperatorsMixin generates __add__, __radd__, comparison and the other operators from __array_ufunc__. Without it, 1 + temps fails with a plain Python TypeError because the class defines no operators.

  • The unwrap helper recurses into lists, because np.concatenate receives a list of containers as one argument. Forgetting this in __array_function__ leads to infinite recursion, since the function calls itself again with the same wrapped objects.

  • Declining reduce and out= returns NotImplemented, which gives the standard TypeError. Production wrappers (Dask, CuPy) implement the methods they can support.

  • numpy.testing.overrides lists what is overridable (allows_array_ufunc_override, allows_array_function_override and the two get_overridable_numpy_* functions). User-defined ufuncs and functions from other libraries are not in those sets.

pandas is the everyday example. A Series implements __array_ufunc__, so np.exp(series) returns a Series with its index intact, while np.asarray(series) returns a plain read-only ndarray under pandas Copy-on-Write (observed here: flags.writeable is False, and series.to_numpy() may also be a view you must not write to). Dask arrays implement __array__ and __array_ufunc__ and stay lazy, and CuPy arrays implement both dispatch protocols so that np.mean(cupy_array) runs on the GPU. PyTorch tensors implement neither dispatch protocol; np.exp(tensor) happens to work through __array__ and __array_wrap__, but the official guide recommends against mixing the two, since it fails for tensors that are not on the CPU and has surprising corner cases. Convert explicitly instead.

Returning your own type: __array_wrap__, __array_finalize__ and __array_priority__

These three hooks matter when you subclass ndarray or wrap one.

  • __array_finalize__ runs whenever NumPy allocates a new array from an instance of your subclass (slicing, views, ufunc results). Use it to copy attributes from the parent.

  • __array_wrap__ is called on the input with the highest __array_priority__ (or on the explicit out) to turn the plain ndarray result into your type and update its metadata. The official guide describes it as the opposite of __array__. Its signature is __array_wrap__(array, context=None, return_scalar=False); the return_scalar argument was added in NumPy 2.0, so older signatures without it should be updated.

  • __array_priority__ decides which type wins when several are possible. When __array_ufunc__ is defined it takes precedence.

NumPy 2.5 deprecates two habits in subclasses (custom dtype properties, and certain uses of __array_finalize__); subclasses with dtype-specific logic should set _set_dtype = None or define _set_dtype as a function that calls ndarray._set_dtype(). Subclassing is rarely the best design: prefer a wrapper that implements the protocols above, or a plain array plus a pandas object. The details are in the official page Subclassing ndarray.

Which mechanism should I use?

Goal Use

View a library’s memory without copying

The buffer protocol, np.frombuffer, np.asarray, memoryview

Make my container acceptable to np.asarray

__array__(self, dtype=None, copy=None)

Share memory with another array library or a GPU framework

np.from_dlpack and __dlpack__

Run NumPy functions inside my own array type

__array_ufunc__ and __array_function__, plus NDArrayOperatorsMixin

Keep my subclass after a NumPy operation

__array_finalize__, __array_wrap__

Write code that works on NumPy, CuPy, PyTorch or JAX arrays alike

The array API standard, see The Array API Standard