GeezerVison is showing github.com — DOC: Clarify dtype argument for __array__ in custom container guide (… · numpy/numpy@1fefc5c
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: doc/source/user/basics.dispatch.rst +15Lines changed: 15 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -46,6 +46,21 @@ array([[1., 0., 0., 0., 0.], | 46 | 46 | [0., 0., 0., 1., 0.], | 47 | 47 | [0., 0., 0., 0., 1.]]) | 48 | 48 |
| | 49 | +The ``__array__`` method can optionally accept a `dtype` argument. If provided, | | 50 | +this argument specifies the desired data type for the resulting NumPy array. | | 51 | +Your implementation should attempt to convert the data to this `dtype` | | 52 | +if possible. If the conversion is not supported, it's generally best | | 53 | +to fall back to a default type or raise a `TypeError` or `ValueError`. | | 54 | + | | 55 | +Here's an example demonstrating its use with `dtype` specification: | | 56 | + | | 57 | +>>> np.asarray(arr, dtype=np.float32) | | 58 | +array([[1., 0., 0., 0., 0.], | | 59 | + [0., 1., 0., 0., 0.], | | 60 | + [0., 0., 1., 0., 0.], | | 61 | + [0., 0., 0., 1., 0.], | | 62 | + [0., 0., 0., 0., 1.]], dtype=float32) | | 63 | + | 49 | 64 | If we operate on ``arr`` with a numpy function, numpy will again use the | 50 | 65 | ``__array__`` interface to convert it to an array and then apply the function | 51 | 66 | in the usual way. | |
|