Skip to content
Merged
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 CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
- The `inner`, `dot` and `einsum` functions can also return a scalar instead of a zero-dimensional array to match NumPy's types ([#285](https://github.com/PyO3/rust-numpy/pull/285))
- The `PyArray::resize` function supports n-dimensional contiguous arrays. ([#312](https://github.com/PyO3/rust-numpy/pull/312))
- Deprecate `PyArray::from_exact_iter` after optimizing `PyArray::from_iter`. ([#292](https://github.com/PyO3/rust-numpy/pull/292))
- Remove `DimensionalityError` and `TypeError` from the public API as they never used directly. ([#315](https://github.com/PyO3/rust-numpy/pull/315))
- Fix returning invalid slices from `PyArray::{strides,shape}` for rank zero arrays. ([#303](https://github.com/PyO3/rust-numpy/pull/303))

- v0.16.2
Expand Down
24 changes: 23 additions & 1 deletion benches/array.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,29 @@ use test::{black_box, Bencher};
use std::ops::Range;

use numpy::{PyArray1, PyArray2, PyArray3};
use pyo3::{Python, ToPyObject};
use pyo3::{PyAny, Python, ToPyObject};

#[bench]
fn extract_success(bencher: &mut Bencher) {
Python::with_gil(|py| {
let any: &PyAny = PyArray2::<f64>::zeros(py, (10, 10), false);

bencher.iter(|| {
black_box(any).extract::<&PyArray2<f64>>().unwrap();
});
});
}

#[bench]
fn extract_failure(bencher: &mut Bencher) {
Python::with_gil(|py| {
let any: &PyAny = PyArray2::<i32>::zeros(py, (10, 10), false);

bencher.iter(|| {
black_box(any).extract::<&PyArray2<f64>>().unwrap_err();
});
});
}

struct Iter(Range<usize>);

Expand Down
53 changes: 36 additions & 17 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
use std::error::Error;
use std::fmt;

use pyo3::{exceptions::PyTypeError, PyErr, PyErrArguments, PyObject, Python, ToPyObject};
use pyo3::{exceptions::PyTypeError, Py, PyErr, PyErrArguments, PyObject, Python, ToPyObject};

use crate::dtype::PyArrayDescr;

Expand Down Expand Up @@ -59,32 +59,51 @@ impl_pyerr!(DimensionalityError);

/// Represents that types of the given arrays do not match.
#[derive(Debug)]
pub struct TypeError {
from: String,
to: String,
pub struct TypeError<'a> {

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly, this addition of a lifetime parameter to TypeError means this cannot be part of a maintenance release because TypeError is part of the crate API even it is not part of any type signature as it is only ever produced wrapped within PyErr. :-(

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Decided to actually remove DimensionalityError and TypeError from the API. They are never used directly and cannot be recovered via downcasting either. So the additional API surface does not gain us anything.

from: &'a PyArrayDescr,
to: &'a PyArrayDescr,
}

impl TypeError {
pub(crate) fn new(from: &PyArrayDescr, to: &PyArrayDescr) -> Self {
let dtype_to_str = |dtype: &PyArrayDescr| {
dtype
.str()
.map_or_else(|_| "(unknown)".into(), |s| s.to_string_lossy().into_owned())
};
Self {
from: dtype_to_str(from),
to: dtype_to_str(to),
}
impl<'a> TypeError<'a> {
pub(crate) fn new(from: &'a PyArrayDescr, to: &'a PyArrayDescr) -> Self {
Self { from, to }
}
}

impl fmt::Display for TypeError {
impl fmt::Display for TypeError<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "type mismatch:\n from={}, to={}", self.from, self.to)
}
}

impl_pyerr!(TypeError);
impl Error for TypeError<'_> {}

struct TypeErrorArguments {
from: Py<PyArrayDescr>,
to: Py<PyArrayDescr>,
}

impl PyErrArguments for TypeErrorArguments {
fn arguments(self, py: Python) -> PyObject {
let err = TypeError {
from: self.from.as_ref(py),
to: self.to.as_ref(py),
};

err.to_string().to_object(py)
}
}

impl From<TypeError<'_>> for PyErr {
fn from(err: TypeError<'_>) -> PyErr {
let args = TypeErrorArguments {
from: err.from.into(),
to: err.to.into(),
};

PyTypeError::new_err(args)
}
}

/// Represents that given `Vec` cannot be treated as an array.
#[derive(Debug)]
Expand Down
4 changes: 1 addition & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,7 @@ pub use crate::borrow::{
};
pub use crate::convert::{IntoPyArray, NpyIndex, ToNpyDims, ToPyArray};
pub use crate::dtype::{dtype, Complex32, Complex64, Element, PyArrayDescr};
pub use crate::error::{
BorrowError, DimensionalityError, FromVecError, NotContiguousError, TypeError,
};
pub use crate::error::{BorrowError, FromVecError, NotContiguousError};
pub use crate::npyffi::{PY_ARRAY_API, PY_UFUNC_API};
#[allow(deprecated)]
pub use crate::npyiter::{
Expand Down