Skip to content

Commit

Permalink
Rename PyConcreteException::py_err to new_err
Browse files Browse the repository at this point in the history
  • Loading branch information
davidhewitt committed Aug 30, 2020
1 parent 80ea2e4 commit 3d33360
Show file tree
Hide file tree
Showing 22 changed files with 69 additions and 89 deletions.
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Change `PyErr::print()` and `PyErr::print_and_set_sys_last_vars()` to take `&self` instead of `self`.
- Remove `PyErr::from_value`, `PyErr::into_normalized()` and `PyErr::normalize()`.
- Change `PyErrValue` to be a private type.
- Remove `PyException::into()` and `Into<PyResult<T>>` for `PyErr` and `PyException`.
- Rename `PyException::py_err()` to `PyException::new_err()`.
- Rename `PyUnicodeDecodeErr::new_err()` to `PyUnicodeDecodeErr::new()`.


### Removed
Expand Down
10 changes: 5 additions & 5 deletions guide/src/exception.md
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ If you already have a Python exception instance, you can simply call [`PyErr::fr
PyErr::from_instance(py, err).restore(py);
```

If a Rust type exists for the exception, then it is possible to use the `py_err` method.
If a Rust type exists for the exception, then it is possible to use the `new_err` method.
For example, each standard exception defined in the `pyo3::exceptions` module
has a corresponding Rust type, exceptions defined by [`create_exception!`] and [`import_exception!`] macro
have Rust types as well.
Expand All @@ -87,7 +87,7 @@ have Rust types as well.
# fn check_for_error() -> bool {false}
fn my_func(arg: PyObject) -> PyResult<()> {
if check_for_error() {
Err(PyValueError::py_err("argument is wrong"))
Err(PyValueError::new_err("argument is wrong"))
} else {
Ok(())
}
Expand Down Expand Up @@ -123,7 +123,7 @@ To check the type of an exception, you can simply do:
# fn main() {
# let gil = Python::acquire_gil();
# let py = gil.python();
# let err = PyTypeError::py_err(());
# let err = PyTypeError::new_err(());
err.is_instance::<PyTypeError>(py);
# }
```
Expand Down Expand Up @@ -170,7 +170,7 @@ until a `Python` object is available.
# }
impl std::convert::From<CustomIOError> for PyErr {
fn from(err: CustomIOError) -> PyErr {
PyOSError::py_err(err.to_string())
PyOSError::new_err(err.to_string())
}
}

Expand Down Expand Up @@ -213,7 +213,7 @@ fn tell(file: &PyAny) -> PyResult<u64> {
use pyo3::exceptions::*;

match file.call_method0("tell") {
Err(_) => Err(io::UnsupportedOperation::py_err("not supported: tell")),
Err(_) => Err(io::UnsupportedOperation::new_err("not supported: tell")),
Ok(x) => x.extract::<u64>(),
}
}
Expand Down
12 changes: 6 additions & 6 deletions src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -156,10 +156,10 @@ pub unsafe trait Element: Copy {
fn validate(b: &ffi::Py_buffer) -> PyResult<()> {
// shape and stride information must be provided when we use PyBUF_FULL_RO
if b.shape.is_null() {
return Err(exceptions::PyBufferError::py_err("Shape is Null"));
return Err(exceptions::PyBufferError::new_err("Shape is Null"));
}
if b.strides.is_null() {
return Err(exceptions::PyBufferError::py_err(
return Err(exceptions::PyBufferError::new_err(
"PyBuffer: Strides is Null",
));
}
Expand Down Expand Up @@ -190,7 +190,7 @@ impl<T: Element> PyBuffer<T> {
{
Ok(buf)
} else {
Err(exceptions::PyBufferError::py_err(
Err(exceptions::PyBufferError::new_err(
"Incompatible type as buffer",
))
}
Expand Down Expand Up @@ -441,7 +441,7 @@ impl<T: Element> PyBuffer<T> {

fn copy_to_slice_impl(&self, py: Python, target: &mut [T], fort: u8) -> PyResult<()> {
if mem::size_of_val(target) != self.len_bytes() {
return Err(exceptions::PyBufferError::py_err(
return Err(exceptions::PyBufferError::new_err(
"Slice length does not match buffer length.",
));
}
Expand Down Expand Up @@ -528,7 +528,7 @@ impl<T: Element> PyBuffer<T> {
return buffer_readonly_error();
}
if mem::size_of_val(source) != self.len_bytes() {
return Err(exceptions::PyBufferError::py_err(
return Err(exceptions::PyBufferError::new_err(
"Slice length does not match buffer length.",
));
}
Expand Down Expand Up @@ -564,7 +564,7 @@ impl<T: Element> PyBuffer<T> {

#[inline(always)]
fn buffer_readonly_error() -> PyResult<()> {
Err(exceptions::PyBufferError::py_err(
Err(exceptions::PyBufferError::new_err(
"Cannot write to read-only buffer.",
))
}
Expand Down
8 changes: 4 additions & 4 deletions src/callback.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ impl IntoPyCallbackOutput<ffi::Py_ssize_t> for usize {
if self <= (isize::MAX as usize) {
Ok(self as isize)
} else {
Err(PyOverflowError::py_err(()))
Err(PyOverflowError::new_err(()))
}
}
}
Expand Down Expand Up @@ -244,11 +244,11 @@ macro_rules! callback_body_without_convert {
Err(e) => {
// Try to format the error in the same way panic does
if let Some(string) = e.downcast_ref::<String>() {
Err($crate::panic::PanicException::py_err((string.clone(),)))
Err($crate::panic::PanicException::new_err((string.clone(),)))
} else if let Some(s) = e.downcast_ref::<&str>() {
Err($crate::panic::PanicException::py_err((s.to_string(),)))
Err($crate::panic::PanicException::new_err((s.to_string(),)))
} else {
Err($crate::panic::PanicException::py_err((
Err($crate::panic::PanicException::new_err((
"panic from Rust code",
)))
}
Expand Down
2 changes: 1 addition & 1 deletion src/class/iter.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ impl IntoPyCallbackOutput<*mut ffi::PyObject> for PyIterNextOutput {
fn convert(self, _py: Python) -> PyResult<*mut ffi::PyObject> {
match self {
IterNextOutput::Yield(o) => Ok(o.into_ptr()),
IterNextOutput::Return(opt) => Err(crate::exceptions::PyStopIteration::py_err((opt,))),
IterNextOutput::Return(opt) => Err(crate::exceptions::PyStopIteration::new_err((opt,))),
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/class/pyasync.rs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ impl IntoPyCallbackOutput<*mut ffi::PyObject> for PyIterANextOutput {
match self {
IterANextOutput::Yield(o) => Ok(o.into_ptr()),
IterANextOutput::Return(opt) => {
Err(crate::exceptions::PyStopAsyncIteration::py_err((opt,)))
Err(crate::exceptions::PyStopAsyncIteration::new_err((opt,)))
}
}
}
Expand Down
2 changes: 1 addition & 1 deletion src/derive_utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ pub fn parse_fn_args<'p>(
let nargs = args.len();
let mut used_args = 0;
macro_rules! raise_error {
($s: expr $(,$arg:expr)*) => (return Err(PyTypeError::py_err(format!(
($s: expr $(,$arg:expr)*) => (return Err(PyTypeError::new_err(format!(
concat!("{} ", $s), fname.unwrap_or("function") $(,$arg)*
))))
}
Expand Down
24 changes: 8 additions & 16 deletions src/err/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ impl PyErr {
/// In most cases, you can use a concrete exception's constructors instead:
/// the example is equivalent to
/// ```ignore
/// return Err(exceptions::PyTypeError::py_err("Error message"));
/// return exceptions::PyTypeError::into("Error message");
/// return Err(exceptions::PyTypeError::new_err("Error message"));
/// ```
pub fn new<T, V>(value: V) -> PyErr
where
Expand Down Expand Up @@ -174,7 +173,7 @@ impl PyErr {
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::py_err(("some type error",));
/// let err = PyTypeError::new_err(("some type error",));
/// assert_eq!(err.ptype(py), PyType::new::<PyTypeError>(py));
/// });
/// ```
Expand All @@ -190,7 +189,7 @@ impl PyErr {
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::py_err(("some type error",));
/// let err = PyTypeError::new_err(("some type error",));
/// assert_eq!(err.pvalue(py).to_string(), "TypeError: some type error");
/// });
/// ```
Expand All @@ -206,7 +205,7 @@ impl PyErr {
/// ```rust
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
/// Python::with_gil(|py| {
/// let err = PyTypeError::py_err(("some type error",));
/// let err = PyTypeError::new_err(("some type error",));
/// assert_eq!(err.ptraceback(py), None);
/// });
/// ```
Expand Down Expand Up @@ -426,7 +425,7 @@ impl PyErr {
ptype: Py::from_owned_ptr_or_opt(py, ptype)
.unwrap_or_else(|| exceptions::PySystemError::type_object(py).into()),
pvalue: Py::from_owned_ptr_or_opt(py, pvalue).unwrap_or_else(|| {
exceptions::PySystemError::py_err("Exception value missing")
exceptions::PySystemError::new_err("Exception value missing")
.instance(py)
.into_py(py)
}),
Expand Down Expand Up @@ -476,7 +475,7 @@ impl<'a> IntoPy<PyObject> for &'a PyErr {
/// Convert `PyDowncastError` to Python `TypeError`.
impl<'a> std::convert::From<PyDowncastError<'a>> for PyErr {
fn from(err: PyDowncastError) -> PyErr {
exceptions::PyTypeError::py_err(err.to_string())
exceptions::PyTypeError::new_err(err.to_string())
}
}

Expand All @@ -496,13 +495,6 @@ impl<'a> std::fmt::Display for PyDowncastError<'a> {
}
}

/// Convert `PyErr` to `PyResult<T>`
impl<T> std::convert::Into<PyResult<T>> for PyErr {
fn into(self) -> PyResult<T> {
Err(self)
}
}

pub fn panic_after_error(_py: Python) -> ! {
unsafe {
ffi::PyErr_Print();
Expand Down Expand Up @@ -531,7 +523,7 @@ mod tests {
fn set_typeerror() {
let gil = Python::acquire_gil();
let py = gil.python();
let err: PyErr = exceptions::PyTypeError::py_err(());
let err: PyErr = exceptions::PyTypeError::new_err(());
err.restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
Expand All @@ -549,7 +541,7 @@ mod tests {

let gil = Python::acquire_gil();
let py = gil.python();
let err: PyErr = PanicException::py_err("new panic");
let err: PyErr = PanicException::new_err("new panic");
err.restore(py);
assert!(PyErr::occurred(py));
let started_unwind =
Expand Down
55 changes: 20 additions & 35 deletions src/exceptions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
//! Exception types defined by Python.

use crate::type_object::PySizedLayout;
use crate::types::{PyAny, PyTuple};
use crate::types::PyTuple;
use crate::{ffi, AsPyPointer, PyResult, Python};
use std::ffi::CStr;
use std::ops;
Expand All @@ -19,20 +19,11 @@ macro_rules! impl_exception_boilerplate {
}
}

impl<T> std::convert::Into<$crate::PyResult<T>> for $name {
fn into(self) -> $crate::PyResult<T> {
$crate::PyErr::new::<$name, _>(()).into()
}
}

impl $name {
pub fn py_err<V: $crate::ToPyObject + Send + Sync + 'static>(args: V) -> $crate::PyErr {
$crate::PyErr::new::<$name, V>(args)
}
pub fn into<R, V: $crate::ToPyObject + Send + Sync + 'static>(
pub fn new_err<V: $crate::ToPyObject + Send + Sync + 'static>(
args: V,
) -> $crate::PyResult<R> {
$crate::PyErr::new::<$name, V>(args).into()
) -> $crate::PyErr {
$crate::PyErr::new::<$name, V>(args)
}
}

Expand Down Expand Up @@ -451,13 +442,13 @@ impl_native_exception!(PyIOError, IOError, PyExc_IOError);
impl_native_exception!(PyWindowsError, WindowsError, PyExc_WindowsError);

impl PyUnicodeDecodeError {
pub fn new_err<'p>(
pub fn new<'p>(
py: Python<'p>,
encoding: &CStr,
input: &[u8],
range: ops::Range<usize>,
reason: &CStr,
) -> PyResult<&'p PyAny> {
) -> PyResult<&'p PyUnicodeDecodeError> {
unsafe {
let input: &[c_char] = &*(input as *const [u8] as *const [c_char]);
py.from_owned_ptr_or_err(ffi::PyUnicodeDecodeError_Create(
Expand All @@ -476,9 +467,9 @@ impl PyUnicodeDecodeError {
py: Python<'p>,
input: &[u8],
err: std::str::Utf8Error,
) -> PyResult<&'p PyAny> {
) -> PyResult<&'p PyUnicodeDecodeError> {
let pos = err.valid_up_to();
PyUnicodeDecodeError::new_err(
PyUnicodeDecodeError::new(
py,
CStr::from_bytes_with_nul(b"utf-8\0").unwrap(),
input,
Expand Down Expand Up @@ -523,7 +514,6 @@ mod test {
use crate::types::{IntoPyDict, PyDict};
use crate::{PyErr, Python};
use std::error::Error;
use std::fmt::Write;

import_exception!(socket, gaierror);
import_exception!(email.errors, MessageError);
Expand All @@ -533,7 +523,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();

let err: PyErr = gaierror::py_err(());
let err: PyErr = gaierror::new_err(());
let socket = py
.import("socket")
.map_err(|e| e.print(py))
Expand All @@ -558,7 +548,7 @@ mod test {
let gil = Python::acquire_gil();
let py = gil.python();

let err: PyErr = MessageError::py_err(());
let err: PyErr = MessageError::new_err(());
let email = py
.import("email")
.map_err(|e| e.print(py))
Expand Down Expand Up @@ -605,35 +595,30 @@ mod test {

#[test]
fn native_exception_display() {
let mut out = String::new();
let gil = Python::acquire_gil();
let py = gil.python();
let err = py
let exc = py
.run("raise Exception('banana')", None, None)
.expect_err("raising should have given us an error");
write!(&mut out, "{}", err.instance(py)).expect("successful format");
assert_eq!(out, "Exception: banana");
.expect_err("raising should have given us an error")
.into_instance(py);
assert_eq!(exc.to_string(), "Exception: banana");
}

#[test]
fn native_exception_chain() {
let mut out = String::new();
let gil = Python::acquire_gil();
let py = gil.python();
let err = py
let exc = py
.run(
"raise Exception('banana') from TypeError('peach')",
None,
None,
)
.expect_err("raising should have given us an error");
let instance = err.instance(py);
write!(&mut out, "{}", instance).expect("successful format");
assert_eq!(out, "Exception: banana");
out.clear();
let source = instance.source().expect("cause should exist");
write!(&mut out, "{}", source).expect("successful format");
assert_eq!(out, "TypeError: peach");
.expect_err("raising should have given us an error")
.into_instance(py);
assert_eq!(exc.to_string(), "Exception: banana");
let source = exc.as_ref(py).source().expect("cause should exist");
assert_eq!(source.to_string(), "TypeError: peach");
let source_source = source.source();
assert!(source_source.is_none(), "source_source should be None");
}
Expand Down
4 changes: 2 additions & 2 deletions src/pycell.rs
Original file line number Diff line number Diff line change
Expand Up @@ -730,7 +730,7 @@ impl fmt::Display for PyBorrowError {

impl From<PyBorrowError> for PyErr {
fn from(other: PyBorrowError) -> Self {
PyRuntimeError::py_err(other.to_string())
PyRuntimeError::new_err(other.to_string())
}
}

Expand All @@ -755,6 +755,6 @@ impl fmt::Display for PyBorrowMutError {

impl From<PyBorrowMutError> for PyErr {
fn from(other: PyBorrowMutError) -> Self {
PyRuntimeError::py_err(other.to_string())
PyRuntimeError::new_err(other.to_string())
}
}
Loading

0 comments on commit 3d33360

Please sign in to comment.