Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/pybind11/numpy.h
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,7 @@ struct npy_api {
NPY_STRING_,
NPY_UNICODE_,
NPY_VOID_,
NPY_HALF_ = 23, // NPY_DATETIME (21) and NPY_TIMEDELTA (22) are not mirrored
Comment thread
advitrocks9 marked this conversation as resolved.
// Platform-dependent normalization
NPY_INT8_ = NPY_BYTE_,
NPY_UINT8_ = NPY_UBYTE_,
Expand Down
19 changes: 19 additions & 0 deletions tests/test_numpy_dtypes.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,21 @@ py::array_t<T> dispatch_array_increment(const py::array_t<T> &arr) {
struct A {};
struct B {};

struct UserHalf {
uint16_t bits;
};

PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
PYBIND11_NAMESPACE_BEGIN(detail)
template <>
struct npy_format_descriptor<UserHalf> {
static constexpr auto name = const_name("numpy.float16");
static constexpr int value = npy_api::NPY_HALF_;
static pybind11::dtype dtype() { return pybind11::dtype(/*typenum*/ value); }
};
PYBIND11_NAMESPACE_END(detail)
PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)

TEST_SUBMODULE(numpy_dtypes, m) {
try {
py::module_::import("numpy");
Expand Down Expand Up @@ -646,6 +661,10 @@ TEST_SUBMODULE(numpy_dtypes, m) {
PYBIND11_NUMPY_DTYPE(TrailingPaddingStruct, a, b);
m.def("trailing_padding_dtype", []() { return py::dtype::of<TrailingPaddingStruct>(); });

// test_half_dtype (issue #4061)
m.def("half_dtype_num", []() { return py::dtype::num_of<UserHalf>(); });
m.def("half_roundtrip", [](const py::array_t<UserHalf> &arr) { return arr; });

// test_string_array
m.def("create_string_array", [](bool non_empty) {
py::array_t<StringStruct, 0> arr = mkarray_via_buffer<StringStruct>(non_empty ? 4 : 0);
Expand Down
7 changes: 7 additions & 0 deletions tests/test_numpy_dtypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,13 @@ def test_dtype(simple_dtype):
assert (m.test_dtype_switch(arr.astype("longdouble")) == arr + 1).all()


def test_half_dtype():
assert m.half_dtype_num() == np.dtype("float16").num

result = m.half_roundtrip(np.array([1.5, 2.25, -3.0], dtype=np.float16))
assert result.dtype == np.float16


def test_templated_dtype():
"""A type spelled with a comma needs PYBIND11_TYPE here."""
plain, renamed = m.templated_dtypes()
Expand Down
Loading