Skip to content

Commit 5ccf9ed

Browse files
committed
Remove unsound custom element example.
1 parent 3fcd194 commit 5ccf9ed

File tree

1 file changed

+4
-33
lines changed

1 file changed

+4
-33
lines changed

src/dtype.rs

Lines changed: 4 additions & 33 deletions
Original file line numberDiff line numberDiff line change
@@ -169,7 +169,7 @@ impl DataType {
169169

170170
/// Represents that a type can be an element of `PyArray`.
171171
///
172-
/// Currently, only integer/float/complex types are supported.
172+
/// Currently, only integer/float/complex/object types are supported.
173173
/// If you come up with a nice implementation for some other types, we're happy to receive your PR :)
174174
/// You may refer to the [numpy document](https://numpy.org/doc/stable/reference/c-api/dtype.html#enumerated-types)
175175
/// for all types that numpy supports.
@@ -184,38 +184,9 @@ impl DataType {
184184
///
185185
/// # Custom element types
186186
///
187-
/// You can implement this trait to manage arrays of custom element types, but they still need to be stored
188-
/// on Python's heap using PyO3's [Py](pyo3::Py) type.
189-
///
190-
/// ```
191-
/// use numpy::{ndarray::Array2, DataType, Element, PyArray, PyArrayDescr, ToPyArray};
192-
/// use pyo3::{pyclass, Py, Python};
193-
///
194-
/// #[pyclass]
195-
/// pub struct CustomElement;
196-
///
197-
/// // The transparent wrapper is necessary as one cannot implement
198-
/// // a foreign trait (`Element`) on a foreign type (`Py`) directly.
199-
/// #[derive(Clone)]
200-
/// #[repr(transparent)]
201-
/// pub struct Wrapper(pub Py<CustomElement>);
202-
///
203-
/// unsafe impl Element for Wrapper {
204-
/// const DATA_TYPE: DataType = DataType::Object;
205-
///
206-
/// fn is_same_type(dtype: &PyArrayDescr) -> bool {
207-
/// dtype.get_datatype() == Some(DataType::Object)
208-
/// }
209-
/// }
210-
///
211-
/// Python::with_gil(|py| {
212-
/// let array = Array2::<Wrapper>::from_shape_fn((2, 3), |(_i, _j)| {
213-
/// Wrapper(Py::new(py, CustomElement).unwrap())
214-
/// });
215-
///
216-
/// let _array: &PyArray<Wrapper, _> = array.to_pyarray(py);
217-
/// });
218-
/// ```
187+
/// Note that it is currently not possible to safely store custom element types of the form `Py<T>` with `T: PyClass`
188+
/// as we only check the data type during downcasting and not the dynamic type of each element stored in the array.
189+
/// Therefore, the only safe type to store in object arrays is `Py<PyAny>` also known as `PyObject` for now.
219190
pub unsafe trait Element: Clone + Send {
220191
/// `DataType` corresponding to this type.
221192
const DATA_TYPE: DataType;

0 commit comments

Comments
 (0)