Skip to content

Commit 9d2d073

Browse files
committed
Update docs re: NumPy scalar types
1 parent 4bfc150 commit 9d2d073

1 file changed

Lines changed: 29 additions & 0 deletions

File tree

docs/advanced/pycpp/numpy.rst

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -205,6 +205,35 @@ prevent many types of unsupported structures, it is still the user's
205205
responsibility to use only "plain" structures that can be safely manipulated as
206206
raw memory without violating invariants.
207207

208+
Scalar types
209+
============
210+
211+
In some cases we may want to accept or return NumPy scalar values such as
212+
``np.float32`` or ``np.uint16``. It is especially important in case of
213+
C-side single-precision floats which by default will be bound to Python's
214+
double-precision builtin floats, causing mismatch in float precision.
215+
216+
Luckily, there's a helper type for this occasion - ``py::numpy_scalar``:
217+
218+
.. code-block:: cpp
219+
220+
m.def("square_float32", [](py::numpy_scalar<float> value) {
221+
float v = value;
222+
return py::make_scalar(v * v);
223+
});
224+
225+
This type is trivially convertible to and from the type it wraps; currently
226+
supported scalar types are NumPy arithmetic types: ``bool_``, ``int8``,
227+
``int8``, ``int16``, ``int32``, ``int64``, ``uint8``, ``uint16``, ``uint32``,
228+
``uint64``, ``float32``, ``float64``, all of them mapping to respective C++
229+
equivalents.
230+
231+
.. note::
232+
233+
This is a strict type, it will only allow input arguments of the specified
234+
NumPY type and nothing else (e.g., ``py::numpy_scalar<int64_t>`` will not
235+
accept built-in ``int`` or any other type for that matter).
236+
208237
Vectorizing functions
209238
=====================
210239

0 commit comments

Comments
 (0)