Rename exceptions to PyException etc; reintroduce deprecated ones

This commit is contained in:
David Hewitt 2020-07-04 16:55:26 +01:00
parent a7e0c6bfa7
commit 4ed9748b45
33 changed files with 315 additions and 208 deletions

View File

@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
- Add `Python::with_gil` for executing a closure with the Python GIL. [#1037](https://github.com/PyO3/pyo3/pull/1037)
### Changed
- Exception types have been renamed from e.g. `RuntimeError` to `PyRuntimeError`, and are now only accessible by `&T` or `Py<T>` similar to other Python-native types. The old names continue to exist but are deprecated. [#1024](https://github.com/PyO3/pyo3/pull/1024)
- Correct FFI definitions `Py_SetProgramName` and `Py_SetPythonHome` to take `*const` argument instead of `*mut`. [#1021](https://github.com/PyO3/pyo3/pull/1021)
- Rename `PyString::to_string` to `to_str`, change return type `Cow<str>` to `&str`. [#1023](https://github.com/PyO3/pyo3/pull/1023)
- Correct FFI definition `_PyLong_AsByteArray` `*mut c_uchar` argument instead of `*const c_uchar`. [#1029](https://github.com/PyO3/pyo3/pull/1029)

View File

@ -1,4 +1,4 @@
use pyo3::exceptions::RuntimeError;
use pyo3::exceptions::PyRuntimeError;
use pyo3::prelude::*;
use pyo3::types::PyDict;
@ -33,7 +33,7 @@ impl DictSize {
if seen == self.expected {
Ok(seen)
} else {
Err(PyErr::new::<RuntimeError, _>(format!(
Err(PyErr::new::<PyRuntimeError, _>(format!(
"Expected {} iterations - performed {}",
self.expected, seen
)))

View File

@ -7,7 +7,7 @@ You can use the [`create_exception!`] macro to define a new exception type:
```rust
use pyo3::create_exception;
create_exception!(module, MyError, pyo3::exceptions::Exception);
create_exception!(module, MyError, pyo3::exceptions::PyException);
```
* `module` is the name of the containing module.
@ -19,9 +19,9 @@ For example:
use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::types::IntoPyDict;
use pyo3::exceptions::Exception;
use pyo3::exceptions::PyException;
create_exception!(mymodule, CustomError, Exception);
create_exception!(mymodule, CustomError, PyException);
fn main() {
let gil = Python::acquire_gil();
@ -39,12 +39,12 @@ To raise an exception, first you need to obtain an exception type and construct
```rust
use pyo3::{Python, PyErr};
use pyo3::exceptions;
use pyo3::exceptions::PyTypeError;
fn main() {
let gil = Python::acquire_gil();
let py = gil.python();
PyErr::new::<exceptions::TypeError, _>("Error").restore(py);
PyErr::new::<PyTypeError, _>("Error").restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
}
@ -65,12 +65,12 @@ has a corresponding Rust type, exceptions defined by [`create_exception!`] and [
have Rust types as well.
```rust
# use pyo3::exceptions;
# use pyo3::exceptions::PyValueError;
# use pyo3::prelude::*;
# fn check_for_error() -> bool {false}
fn my_func(arg: PyObject) -> PyResult<()> {
if check_for_error() {
Err(exceptions::ValueError::py_err("argument is wrong"))
Err(PyValueError::py_err("argument is wrong"))
} else {
Ok(())
}
@ -101,13 +101,13 @@ method to do the actual work.
To check the type of an exception, you can simply do:
```rust
# use pyo3::exceptions;
# use pyo3::exceptions::PyTypeError;
# use pyo3::prelude::*;
# fn main() {
# let gil = Python::acquire_gil();
# let py = gil.python();
# let err = exceptions::TypeError::py_err(());
err.is_instance::<exceptions::TypeError>(py);
# let err = PyTypeError::py_err(());
err.is_instance::<PyTypeError>(py);
# }
```
@ -132,7 +132,8 @@ trait can be implemented. In that case, actual exception argument creation is de
until a `Python` object is available.
```rust
# use pyo3::{exceptions, PyErr, PyResult};
# use pyo3::{PyErr, PyResult};
# use pyo3::exceptions::PyOSError;
# use std::error::Error;
# use std::fmt;
#
@ -152,7 +153,7 @@ until a `Python` object is available.
# }
impl std::convert::From<CustomIOError> for PyErr {
fn from(err: CustomIOError) -> PyErr {
exceptions::OSError::py_err(err.to_string())
PyOSError::py_err(err.to_string())
}
}
@ -181,14 +182,15 @@ The code snippet above will raise a `ValueError` in Python if `String::parse()`
## Using exceptions defined in Python code
It is possible to use an exception defined in Python code as a native Rust type.
The `import_exception!` macro allows importing a specific exception class and defines a zero-sized Rust type
The `import_exception!` macro allows importing a specific exception class and defines a Rust type
for that exception.
```rust
use pyo3::prelude::*;
use pyo3::import_exception;
import_exception!(io, UnsupportedOperation);
mod io {
pyo3::import_exception!(io, UnsupportedOperation);
}
fn tell(file: PyObject) -> PyResult<u64> {
use pyo3::exceptions::*;
@ -197,7 +199,7 @@ fn tell(file: PyObject) -> PyResult<u64> {
let py = gil.python();
match file.call_method0(py, "tell") {
Err(_) => Err(UnsupportedOperation::py_err("not supported: tell")),
Err(_) => Err(io::UnsupportedOperation::py_err("not supported: tell")),
Ok(x) => x.extract::<u64>(py),
}
}

View File

@ -156,10 +156,12 @@ 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::BufferError::py_err("Shape is Null"));
return Err(exceptions::PyBufferError::py_err("Shape is Null"));
}
if b.strides.is_null() {
return Err(exceptions::BufferError::py_err("PyBuffer: Strides is Null"));
return Err(exceptions::PyBufferError::py_err(
"PyBuffer: Strides is Null",
));
}
Ok(())
}
@ -188,7 +190,7 @@ impl<T: Element> PyBuffer<T> {
{
Ok(buf)
} else {
Err(exceptions::BufferError::py_err(
Err(exceptions::PyBufferError::py_err(
"Incompatible type as buffer",
))
}
@ -439,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::BufferError::py_err(
return Err(exceptions::PyBufferError::py_err(
"Slice length does not match buffer length.",
));
}
@ -526,7 +528,7 @@ impl<T: Element> PyBuffer<T> {
return buffer_readonly_error();
}
if mem::size_of_val(source) != self.len_bytes() {
return Err(exceptions::BufferError::py_err(
return Err(exceptions::PyBufferError::py_err(
"Slice length does not match buffer length.",
));
}
@ -562,7 +564,7 @@ impl<T: Element> PyBuffer<T> {
#[inline(always)]
fn buffer_readonly_error() -> PyResult<()> {
Err(exceptions::BufferError::py_err(
Err(exceptions::PyBufferError::py_err(
"Cannot write to read-only buffer.",
))
}

View File

@ -3,7 +3,7 @@
//! Utilities for a Python callable object that invokes a Rust function.
use crate::err::PyResult;
use crate::exceptions::OverflowError;
use crate::exceptions::PyOverflowError;
use crate::ffi::{self, Py_hash_t};
use crate::IntoPyPointer;
use crate::{IntoPy, PyObject, Python};
@ -85,7 +85,7 @@ impl IntoPyCallbackOutput<ffi::Py_ssize_t> for usize {
if self <= (isize::MAX as usize) {
Ok(self as isize)
} else {
Err(OverflowError::py_err(()))
Err(PyOverflowError::py_err(()))
}
}
}

View File

@ -260,7 +260,7 @@ where
ffi::Py_NE => Ok(CompareOp::Ne),
ffi::Py_GT => Ok(CompareOp::Gt),
ffi::Py_GE => Ok(CompareOp::Ge),
_ => Err(PyErr::new::<exceptions::ValueError, _>(
_ => Err(PyErr::new::<exceptions::PyValueError, _>(
"tp_richcompare called with invalid comparison operator",
)),
}

View File

@ -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::StopIteration::py_err((opt,))),
IterNextOutput::Return(opt) => Err(crate::exceptions::PyStopIteration::py_err((opt,))),
}
}
}

View File

@ -302,7 +302,7 @@ macro_rules! py_func_set {
let slf = py.from_borrowed_ptr::<$crate::PyCell<$generic>>(slf);
if value.is_null() {
Err($crate::PyErr::new::<exceptions::NotImplementedError, _>(
Err($crate::PyErr::new::<exceptions::PyNotImplementedError, _>(
format!(
"Subscript deletion not supported by {:?}",
stringify!($generic)
@ -338,7 +338,7 @@ macro_rules! py_func_del {
.extract()?;
slf.try_borrow_mut()?.$fn_del(name).convert(py)
} else {
Err(PyErr::new::<exceptions::NotImplementedError, _>(
Err(PyErr::new::<exceptions::PyNotImplementedError, _>(
"Subscript assignment not supported",
))
}

View File

@ -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::StopAsyncIteration::py_err((opt,)))
Err(crate::exceptions::PyStopAsyncIteration::py_err((opt,)))
}
}
}

View File

@ -223,7 +223,7 @@ mod sq_ass_item_impl {
let slf = py.from_borrowed_ptr::<PyCell<T>>(slf);
if value.is_null() {
return Err(PyErr::new::<exceptions::NotImplementedError, _>(format!(
return Err(PyErr::new::<exceptions::PyNotImplementedError, _>(format!(
"Item deletion is not supported by {:?}",
stringify!(T)
)));
@ -256,7 +256,7 @@ mod sq_ass_item_impl {
if value.is_null() {
crate::callback::convert(py, slf.borrow_mut().__delitem__(key.into()))
} else {
Err(PyErr::new::<exceptions::NotImplementedError, _>(format!(
Err(PyErr::new::<exceptions::PyNotImplementedError, _>(format!(
"Item assignment not supported by {:?}",
stringify!(T)
)))

View File

@ -5,7 +5,7 @@
//! Functionality for the code generated by the derive backend
use crate::err::{PyErr, PyResult};
use crate::exceptions::TypeError;
use crate::exceptions::PyTypeError;
use crate::instance::PyNativeType;
use crate::pyclass::{PyClass, PyClassThreadChecker};
use crate::types::{PyAny, PyDict, PyModule, PyTuple};
@ -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(TypeError::py_err(format!(
($s: expr $(,$arg:expr)*) => (return Err(PyTypeError::py_err(format!(
concat!("{} ", $s), fname.unwrap_or("function") $(,$arg)*
))))
}

View File

@ -75,14 +75,14 @@ impl PyErr {
///
/// Example:
/// ```ignore
/// return Err(PyErr::new::<exceptions::TypeError, _>("Error message"));
/// return Err(PyErr::new::<exceptions::PyTypeError, _>("Error message"));
/// ```
///
/// In most cases, you can use a concrete exception's constructors instead:
/// the example is equivalent to
/// ```ignore
/// return Err(exceptions::TypeError::py_err("Error message"));
/// return exceptions::TypeError::into("Error message");
/// return Err(exceptions::PyTypeError::py_err("Error message"));
/// return exceptions::PyTypeError::into("Error message");
/// ```
pub fn new<T, V>(value: V) -> PyErr
where
@ -105,7 +105,7 @@ impl PyErr {
/// Constructs a new error, with the usual lazy initialization of Python exceptions.
///
/// `exc` is the exception type; usually one of the standard exceptions
/// like `exceptions::RuntimeError`.
/// like `exceptions::PyRuntimeError`.
/// `args` is the a tuple of arguments to pass to the exception constructor.
pub fn from_type<A>(exc: &PyType, args: A) -> PyErr
where
@ -161,7 +161,7 @@ impl PyErr {
}
} else {
PyErr {
ptype: exceptions::TypeError::type_object(obj.py()).into(),
ptype: exceptions::PyTypeError::type_object(obj.py()).into(),
pvalue: PyErrValue::ToObject(Box::new("exceptions must derive from BaseException")),
ptraceback: None,
}
@ -257,7 +257,7 @@ impl PyErr {
};
let ptype = if ptype.is_null() {
<exceptions::SystemError as PyTypeObject>::type_object(py).into()
<exceptions::PySystemError as PyTypeObject>::type_object(py).into()
} else {
Py::from_owned_ptr(py, ptype)
};
@ -344,7 +344,7 @@ impl PyErr {
///
/// This method takes `mut self` because the error might need
/// to be normalized in order to create the exception instance.
pub fn instance(mut self, py: Python) -> &exceptions::BaseException {
pub fn instance(mut self, py: Python) -> &exceptions::PyBaseException {
self.normalize(py);
match self.pvalue {
PyErrValue::Value(ref instance) => {
@ -439,7 +439,7 @@ impl FromPy<PyErr> for PyObject {
}
}
impl FromPy<PyErr> for Py<exceptions::BaseException> {
impl FromPy<PyErr> for Py<exceptions::PyBaseException> {
fn from_py(other: PyErr, py: Python) -> Self {
other.instance(py).into()
}
@ -462,7 +462,7 @@ impl<'a> IntoPy<PyObject> for &'a PyErr {
/// Convert `PyDowncastError` to Python `TypeError`.
impl std::convert::From<PyDowncastError> for PyErr {
fn from(_err: PyDowncastError) -> PyErr {
exceptions::TypeError::py_err(())
exceptions::PyTypeError::py_err(())
}
}
@ -515,28 +515,30 @@ impl std::convert::From<io::Error> for PyErr {
}
match err.kind() {
io::ErrorKind::BrokenPipe => {
PyErr::from_value::<exceptions::BrokenPipeError>(err_value!())
PyErr::from_value::<exceptions::PyBrokenPipeError>(err_value!())
}
io::ErrorKind::ConnectionRefused => {
PyErr::from_value::<exceptions::ConnectionRefusedError>(err_value!())
PyErr::from_value::<exceptions::PyConnectionRefusedError>(err_value!())
}
io::ErrorKind::ConnectionAborted => {
PyErr::from_value::<exceptions::ConnectionAbortedError>(err_value!())
PyErr::from_value::<exceptions::PyConnectionAbortedError>(err_value!())
}
io::ErrorKind::ConnectionReset => {
PyErr::from_value::<exceptions::ConnectionResetError>(err_value!())
PyErr::from_value::<exceptions::PyConnectionResetError>(err_value!())
}
io::ErrorKind::Interrupted => {
PyErr::from_value::<exceptions::InterruptedError>(err_value!())
PyErr::from_value::<exceptions::PyInterruptedError>(err_value!())
}
io::ErrorKind::NotFound => {
PyErr::from_value::<exceptions::FileNotFoundError>(err_value!())
PyErr::from_value::<exceptions::PyFileNotFoundError>(err_value!())
}
io::ErrorKind::WouldBlock => {
PyErr::from_value::<exceptions::BlockingIOError>(err_value!())
PyErr::from_value::<exceptions::PyBlockingIOError>(err_value!())
}
io::ErrorKind::TimedOut => PyErr::from_value::<exceptions::TimeoutError>(err_value!()),
_ => PyErr::from_value::<exceptions::OSError>(err_value!()),
io::ErrorKind::TimedOut => {
PyErr::from_value::<exceptions::PyTimeoutError>(err_value!())
}
_ => PyErr::from_value::<exceptions::PyOSError>(err_value!()),
}
}
}
@ -549,7 +551,7 @@ impl PyErrArguments for io::Error {
impl<W: 'static + Send + std::fmt::Debug> std::convert::From<std::io::IntoInnerError<W>> for PyErr {
fn from(err: std::io::IntoInnerError<W>) -> PyErr {
PyErr::from_value::<exceptions::OSError>(PyErrValue::from_err_args(err))
PyErr::from_value::<exceptions::PyOSError>(PyErrValue::from_err_args(err))
}
}
@ -567,22 +569,28 @@ impl PyErrArguments for std::convert::Infallible {
impl std::convert::From<std::convert::Infallible> for PyErr {
fn from(_: std::convert::Infallible) -> PyErr {
PyErr::new::<exceptions::ValueError, _>("Infalliable!")
PyErr::new::<exceptions::PyValueError, _>("Infalliable!")
}
}
impl_to_pyerr!(std::array::TryFromSliceError, exceptions::ValueError);
impl_to_pyerr!(std::num::ParseIntError, exceptions::ValueError);
impl_to_pyerr!(std::num::ParseFloatError, exceptions::ValueError);
impl_to_pyerr!(std::num::TryFromIntError, exceptions::ValueError);
impl_to_pyerr!(std::str::ParseBoolError, exceptions::ValueError);
impl_to_pyerr!(std::ffi::IntoStringError, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::ffi::NulError, exceptions::ValueError);
impl_to_pyerr!(std::str::Utf8Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::string::FromUtf8Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::string::FromUtf16Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::char::DecodeUtf16Error, exceptions::UnicodeDecodeError);
impl_to_pyerr!(std::net::AddrParseError, exceptions::ValueError);
impl_to_pyerr!(std::array::TryFromSliceError, exceptions::PyValueError);
impl_to_pyerr!(std::num::ParseIntError, exceptions::PyValueError);
impl_to_pyerr!(std::num::ParseFloatError, exceptions::PyValueError);
impl_to_pyerr!(std::num::TryFromIntError, exceptions::PyValueError);
impl_to_pyerr!(std::str::ParseBoolError, exceptions::PyValueError);
impl_to_pyerr!(std::ffi::IntoStringError, exceptions::PyUnicodeDecodeError);
impl_to_pyerr!(std::ffi::NulError, exceptions::PyValueError);
impl_to_pyerr!(std::str::Utf8Error, exceptions::PyUnicodeDecodeError);
impl_to_pyerr!(std::string::FromUtf8Error, exceptions::PyUnicodeDecodeError);
impl_to_pyerr!(
std::string::FromUtf16Error,
exceptions::PyUnicodeDecodeError
);
impl_to_pyerr!(
std::char::DecodeUtf16Error,
exceptions::PyUnicodeDecodeError
);
impl_to_pyerr!(std::net::AddrParseError, exceptions::PyValueError);
pub fn panic_after_error(_py: Python) -> ! {
unsafe {
@ -611,7 +619,7 @@ mod tests {
fn set_typeerror() {
let gil = Python::acquire_gil();
let py = gil.python();
let err: PyErr = exceptions::TypeError::py_err(());
let err: PyErr = exceptions::PyTypeError::py_err(());
err.restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));

View File

@ -2,8 +2,8 @@
//! Exception types defined by Python.
use crate::types::{PyAny, PyTuple};
use crate::type_object::PySizedLayout;
use crate::types::{PyAny, PyTuple};
use crate::{ffi, AsPyPointer, PyResult, Python};
use std::ffi::CStr;
use std::ops;
@ -65,7 +65,7 @@ macro_rules! impl_exception_boilerplate {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
unsafe {
use $crate::{AsPyPointer, PyNativeType};
let cause: &$crate::exceptions::BaseException = self
let cause: &$crate::exceptions::PyBaseException = self
.py()
.from_owned_ptr_or_opt($crate::ffi::PyException_GetCause(self.as_ptr()))?;
@ -132,7 +132,7 @@ macro_rules! import_exception {
unsafe fn check(ptr: *mut $crate::ffi::PyObject) -> $crate::libc::c_int {
$crate::ffi::PyObject_TypeCheck(
ptr,
Self::type_object_raw($crate::Python::assume_gil_acquired()) as *mut _
Self::type_object_raw($crate::Python::assume_gil_acquired()) as *mut _,
)
}
@ -171,16 +171,16 @@ macro_rules! import_exception {
///
/// * `module` is the name of the containing module.
/// * `MyError` is the name of the new exception type.
/// * `BaseException` is the superclass of `MyError`, usually `pyo3::exceptions::Exception`.
/// * `BaseException` is the superclass of `MyError`, usually `pyo3::exceptions::PyException`.
///
/// # Example
/// ```
/// use pyo3::prelude::*;
/// use pyo3::create_exception;
/// use pyo3::types::IntoPyDict;
/// use pyo3::exceptions::Exception;
/// use pyo3::exceptions::PyException;
///
/// create_exception!(mymodule, CustomError, Exception);
/// create_exception!(mymodule, CustomError, PyException);
///
/// fn main() {
/// let gil = Python::acquire_gil();
@ -235,7 +235,7 @@ macro_rules! create_exception_type_object {
unsafe fn check(ptr: *mut $crate::ffi::PyObject) -> $crate::libc::c_int {
$crate::ffi::PyObject_TypeCheck(
ptr,
Self::type_object_raw($crate::Python::assume_gil_acquired()) as *mut _
Self::type_object_raw($crate::Python::assume_gil_acquired()) as *mut _,
)
}
@ -265,9 +265,12 @@ macro_rules! create_exception_type_object {
}
macro_rules! impl_native_exception (
($name:ident, $exc_name:ident, $layout:path) => (
($name:ident, $legacy_name:ident, $exc_name:ident, $layout:path) => (
pub struct $name($crate::PyAny);
#[deprecated(note = "Exceptions now have a `Py` prefix, e.g. `PyException`, `PyTypeError`")]
pub type $legacy_name = $crate::Py<$name>;
$crate::impl_exception_boilerplate!($name);
impl $name {
@ -282,80 +285,168 @@ macro_rules! impl_native_exception (
$crate::pyobject_native_type_core!($name, $layout, *(ffi::$exc_name as *mut ffi::PyTypeObject), Some("builtins"), $name::check);
);
($name:ident, $exc_name:ident) => (
impl_native_exception!($name, $exc_name, ffi::PyBaseExceptionObject);
($name:ident, $legacy_name:ident, $exc_name:ident) => (
impl_native_exception!($name, $legacy_name, $exc_name, ffi::PyBaseExceptionObject);
)
);
impl PySizedLayout<BaseException> for ffi::PyBaseExceptionObject {}
impl PySizedLayout<PyBaseException> for ffi::PyBaseExceptionObject {}
impl_native_exception!(BaseException, PyExc_BaseException);
impl_native_exception!(Exception, PyExc_Exception);
impl_native_exception!(StopAsyncIteration, PyExc_StopAsyncIteration);
impl_native_exception!(PyBaseException, BaseException, PyExc_BaseException);
impl_native_exception!(PyException, Exception, PyExc_Exception);
impl_native_exception!(
PyStopAsyncIteration,
StopAsyncIteration,
PyExc_StopAsyncIteration
);
impl_native_exception!(
PyStopIteration,
StopIteration,
PyExc_StopIteration,
ffi::PyStopIterationObject
);
impl_native_exception!(GeneratorExit, PyExc_GeneratorExit);
impl_native_exception!(ArithmeticError, PyExc_ArithmeticError);
impl_native_exception!(LookupError, PyExc_LookupError);
impl_native_exception!(PyGeneratorExit, GeneratorExit, PyExc_GeneratorExit);
impl_native_exception!(PyArithmeticError, ArithmeticError, PyExc_ArithmeticError);
impl_native_exception!(PyLookupError, LookupError, PyExc_LookupError);
impl_native_exception!(AssertionError, PyExc_AssertionError);
impl_native_exception!(AttributeError, PyExc_AttributeError);
impl_native_exception!(BufferError, PyExc_BufferError);
impl_native_exception!(EOFError, PyExc_EOFError);
impl_native_exception!(FloatingPointError, PyExc_FloatingPointError);
impl_native_exception!(OSError, PyExc_OSError, ffi::PyOSErrorObject);
impl_native_exception!(ImportError, PyExc_ImportError);
impl_native_exception!(PyAssertionError, AssertionError, PyExc_AssertionError);
impl_native_exception!(PyAttributeError, AttributeError, PyExc_AttributeError);
impl_native_exception!(PyBufferError, BufferError, PyExc_BufferError);
impl_native_exception!(PyEOFError, EOFError, PyExc_EOFError);
impl_native_exception!(
PyFloatingPointError,
FloatingPointError,
PyExc_FloatingPointError
);
impl_native_exception!(PyOSError, OSError, PyExc_OSError, ffi::PyOSErrorObject);
impl_native_exception!(PyImportError, ImportError, PyExc_ImportError);
#[cfg(Py_3_6)]
impl_native_exception!(ModuleNotFoundError, PyExc_ModuleNotFoundError);
impl_native_exception!(
PyModuleNotFoundError,
ModuleNotFoundError,
PyExc_ModuleNotFoundError
);
impl_native_exception!(IndexError, PyExc_IndexError);
impl_native_exception!(KeyError, PyExc_KeyError);
impl_native_exception!(KeyboardInterrupt, PyExc_KeyboardInterrupt);
impl_native_exception!(MemoryError, PyExc_MemoryError);
impl_native_exception!(NameError, PyExc_NameError);
impl_native_exception!(OverflowError, PyExc_OverflowError);
impl_native_exception!(RuntimeError, PyExc_RuntimeError);
impl_native_exception!(RecursionError, PyExc_RecursionError);
impl_native_exception!(NotImplementedError, PyExc_NotImplementedError);
impl_native_exception!(SyntaxError, PyExc_SyntaxError, ffi::PySyntaxErrorObject);
impl_native_exception!(ReferenceError, PyExc_ReferenceError);
impl_native_exception!(SystemError, PyExc_SystemError);
impl_native_exception!(SystemExit, PyExc_SystemExit, ffi::PySystemExitObject);
impl_native_exception!(TypeError, PyExc_TypeError);
impl_native_exception!(UnboundLocalError, PyExc_UnboundLocalError);
impl_native_exception!(UnicodeError, PyExc_UnicodeError, ffi::PyUnicodeErrorObject);
impl_native_exception!(UnicodeDecodeError, PyExc_UnicodeDecodeError);
impl_native_exception!(UnicodeEncodeError, PyExc_UnicodeEncodeError);
impl_native_exception!(UnicodeTranslateError, PyExc_UnicodeTranslateError);
impl_native_exception!(ValueError, PyExc_ValueError);
impl_native_exception!(ZeroDivisionError, PyExc_ZeroDivisionError);
impl_native_exception!(PyIndexError, IndexError, PyExc_IndexError);
impl_native_exception!(PyKeyError, KeyError, PyExc_KeyError);
impl_native_exception!(
PyKeyboardInterrupt,
KeyboardInterrupt,
PyExc_KeyboardInterrupt
);
impl_native_exception!(PyMemoryError, MemoryError, PyExc_MemoryError);
impl_native_exception!(PyNameError, NameError, PyExc_NameError);
impl_native_exception!(PyOverflowError, OverflowError, PyExc_OverflowError);
impl_native_exception!(PyRuntimeError, RuntimeError, PyExc_RuntimeError);
impl_native_exception!(PyRecursionError, RecursionError, PyExc_RecursionError);
impl_native_exception!(
PyNotImplementedError,
NotImplementedError,
PyExc_NotImplementedError
);
impl_native_exception!(
PySyntaxError,
SyntaxError,
PyExc_SyntaxError,
ffi::PySyntaxErrorObject
);
impl_native_exception!(PyReferenceError, ReferenceError, PyExc_ReferenceError);
impl_native_exception!(PySystemError, SystemError, PyExc_SystemError);
impl_native_exception!(
PySystemExit,
SystemExit,
PyExc_SystemExit,
ffi::PySystemExitObject
);
impl_native_exception!(PyTypeError, TypeError, PyExc_TypeError);
impl_native_exception!(
PyUnboundLocalError,
UnboundLocalError,
PyExc_UnboundLocalError
);
impl_native_exception!(
PyUnicodeError,
UnicodeError,
PyExc_UnicodeError,
ffi::PyUnicodeErrorObject
);
impl_native_exception!(
PyUnicodeDecodeError,
UnicodeDecodeError,
PyExc_UnicodeDecodeError
);
impl_native_exception!(
PyUnicodeEncodeError,
UnicodeEncodeError,
PyExc_UnicodeEncodeError
);
impl_native_exception!(
PyUnicodeTranslateError,
UnicodeTranslateError,
PyExc_UnicodeTranslateError
);
impl_native_exception!(PyValueError, ValueError, PyExc_ValueError);
impl_native_exception!(
PyZeroDivisionError,
ZeroDivisionError,
PyExc_ZeroDivisionError
);
impl_native_exception!(BlockingIOError, PyExc_BlockingIOError);
impl_native_exception!(BrokenPipeError, PyExc_BrokenPipeError);
impl_native_exception!(ChildProcessError, PyExc_ChildProcessError);
impl_native_exception!(ConnectionError, PyExc_ConnectionError);
impl_native_exception!(ConnectionAbortedError, PyExc_ConnectionAbortedError);
impl_native_exception!(ConnectionRefusedError, PyExc_ConnectionRefusedError);
impl_native_exception!(ConnectionResetError, PyExc_ConnectionResetError);
impl_native_exception!(FileExistsError, PyExc_FileExistsError);
impl_native_exception!(FileNotFoundError, PyExc_FileNotFoundError);
impl_native_exception!(InterruptedError, PyExc_InterruptedError);
impl_native_exception!(IsADirectoryError, PyExc_IsADirectoryError);
impl_native_exception!(NotADirectoryError, PyExc_NotADirectoryError);
impl_native_exception!(PermissionError, PyExc_PermissionError);
impl_native_exception!(ProcessLookupError, PyExc_ProcessLookupError);
impl_native_exception!(TimeoutError, PyExc_TimeoutError);
impl_native_exception!(PyBlockingIOError, BlockingIOError, PyExc_BlockingIOError);
impl_native_exception!(PyBrokenPipeError, BrokenPipeError, PyExc_BrokenPipeError);
impl_native_exception!(
PyChildProcessError,
ChildProcessError,
PyExc_ChildProcessError
);
impl_native_exception!(PyConnectionError, ConnectionError, PyExc_ConnectionError);
impl_native_exception!(
PyConnectionAbortedError,
ConnectionAbortedError,
PyExc_ConnectionAbortedError
);
impl_native_exception!(
PyConnectionRefusedError,
ConnectionRefusedError,
PyExc_ConnectionRefusedError
);
impl_native_exception!(
PyConnectionResetError,
ConnectionResetError,
PyExc_ConnectionResetError
);
impl_native_exception!(PyFileExistsError, FileExistsError, PyExc_FileExistsError);
impl_native_exception!(
PyFileNotFoundError,
FileNotFoundError,
PyExc_FileNotFoundError
);
impl_native_exception!(PyInterruptedError, InterruptedError, PyExc_InterruptedError);
impl_native_exception!(
PyIsADirectoryError,
IsADirectoryError,
PyExc_IsADirectoryError
);
impl_native_exception!(
PyNotADirectoryError,
NotADirectoryError,
PyExc_NotADirectoryError
);
impl_native_exception!(PyPermissionError, PermissionError, PyExc_PermissionError);
impl_native_exception!(
PyProcessLookupError,
ProcessLookupError,
PyExc_ProcessLookupError
);
impl_native_exception!(PyTimeoutError, TimeoutError, PyExc_TimeoutError);
impl_native_exception!(EnvironmentError, PyExc_EnvironmentError);
impl_native_exception!(IOError, PyExc_IOError);
impl_native_exception!(PyEnvironmentError, EnvironmentError, PyExc_EnvironmentError);
impl_native_exception!(PyIOError, IOError, PyExc_IOError);
#[cfg(target_os = "windows")]
impl_native_exception!(WindowsError, PyExc_WindowsError);
impl_native_exception!(PyWindowsError, WindowsError, PyExc_WindowsError);
impl UnicodeDecodeError {
impl PyUnicodeDecodeError {
pub fn new_err<'p>(
py: Python<'p>,
encoding: &CStr,
@ -383,7 +474,7 @@ impl UnicodeDecodeError {
err: std::str::Utf8Error,
) -> PyResult<&'p PyAny> {
let pos = err.valid_up_to();
UnicodeDecodeError::new_err(
PyUnicodeDecodeError::new_err(
py,
CStr::from_bytes_with_nul(b"utf-8\0").unwrap(),
input,
@ -393,7 +484,7 @@ impl UnicodeDecodeError {
}
}
impl StopIteration {
impl PyStopIteration {
pub fn stop_iteration(_py: Python, args: &PyTuple) {
unsafe {
ffi::PyErr_SetObject(
@ -424,7 +515,7 @@ pub mod socket {
#[cfg(test)]
mod test {
use crate::exceptions::Exception;
use crate::exceptions::PyException;
use crate::types::{IntoPyDict, PyDict};
use crate::{AsPyPointer, PyErr, Python};
use std::error::Error;
@ -487,7 +578,7 @@ mod test {
#[test]
fn custom_exception() {
create_exception!(mymodule, CustomError, Exception);
create_exception!(mymodule, CustomError, PyException);
let gil = Python::acquire_gil();
let py = gil.python();
@ -536,7 +627,7 @@ mod test {
write!(&mut out, "{}", err).expect("successful format");
assert_eq!(out, "Exception: banana");
out.clear();
let convert_ref: &super::BaseException =
let convert_ref: &super::PyBaseException =
unsafe { &*(err.as_ptr() as *const _ as *const _) };
let source = convert_ref.source().expect("cause should exist");
write!(&mut out, "{}", source).expect("successful format");

View File

@ -384,13 +384,14 @@ where
impl<T> std::error::Error for Py<T>
where
T: std::error::Error + PyTypeInfo,
T::AsRefTarget: std::fmt::Display
{ }
T::AsRefTarget: std::fmt::Display,
{
}
impl<T> std::fmt::Display for Py<T>
where
T: PyTypeInfo,
T::AsRefTarget: std::fmt::Display
T::AsRefTarget: std::fmt::Display,
{
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let gil = Python::acquire_gil();

View File

@ -1,5 +1,4 @@
use crate::exceptions::BaseException;
use crate::exceptions::PyBaseException;
pyo3_exception!(
"
@ -10,5 +9,5 @@ pyo3_exception!(
Python interpreter to exit.
",
PanicException,
BaseException
);
PyBaseException
);

View File

@ -1,7 +1,7 @@
//! Includes `PyCell` implementation.
use crate::conversion::{AsPyPointer, FromPyPointer, ToPyObject};
use crate::exceptions::PyRuntimeError;
use crate::pyclass::{PyClass, PyClassThreadChecker};
use crate::exceptions::RuntimeError;
use crate::pyclass_init::PyClassInitializer;
use crate::pyclass_slots::{PyClassDict, PyClassWeakRef};
use crate::type_object::{PyBorrowFlagLayout, PyLayout, PySizedLayout, PyTypeInfo};
@ -708,7 +708,7 @@ impl fmt::Display for PyBorrowError {
impl From<PyBorrowError> for PyErr {
fn from(other: PyBorrowError) -> Self {
RuntimeError::py_err(other.to_string())
PyRuntimeError::py_err(other.to_string())
}
}
@ -733,6 +733,6 @@ impl fmt::Display for PyBorrowMutError {
impl From<PyBorrowMutError> for PyErr {
fn from(other: PyBorrowMutError) -> Self {
RuntimeError::py_err(other.to_string())
PyRuntimeError::py_err(other.to_string())
}
}

View File

@ -101,7 +101,7 @@ impl<'p> Python<'p> {
/// # Example
/// ```
/// # use pyo3::prelude::*; use pyo3::types::IntoPyDict; use pyo3::wrap_pyfunction;
/// use pyo3::exceptions::RuntimeError;
/// use pyo3::exceptions::PyRuntimeError;
/// use std::sync::Arc;
/// use std::thread;
/// #[pyfunction]
@ -114,7 +114,7 @@ impl<'p> Python<'p> {
/// .collect();
/// let mut sum = 0;
/// for t in threads {
/// sum += t.join().map_err(|_| PyErr::new::<RuntimeError, _>(()))?;
/// sum += t.join().map_err(|_| PyErr::new::<PyRuntimeError, _>(()))?;
/// }
/// Ok(sum)
/// })

View File

@ -3,7 +3,7 @@ use crate::conversion::{
AsPyPointer, FromPyObject, IntoPy, IntoPyPointer, PyTryFrom, ToBorrowedObject, ToPyObject,
};
use crate::err::{PyDowncastError, PyErr, PyResult};
use crate::exceptions::TypeError;
use crate::exceptions::PyTypeError;
use crate::types::{PyDict, PyIterator, PyList, PyString, PyTuple, PyType};
use crate::{err, ffi, Py, PyNativeType, PyObject};
use libc::c_int;
@ -163,7 +163,7 @@ impl PyAny {
} else if do_compare(other, ffi::Py_GT)? {
Ok(Ordering::Greater)
} else {
Err(TypeError::py_err(
Err(PyTypeError::py_err(
"PyAny::compare(): All comparisons returned false",
))
}

View File

@ -210,7 +210,7 @@ mod test {
let py = gil.python();
if let Err(err) = PyByteArray::from(py, &py.None()) {
assert!(err.is_instance::<exceptions::TypeError>(py));
assert!(err.is_instance::<exceptions::PyTypeError>(py));
} else {
panic!("error");
}

View File

@ -82,7 +82,7 @@ impl PyModule {
match self.getattr("__all__") {
Ok(idx) => idx.downcast().map_err(PyErr::from),
Err(err) => {
if err.is_instance::<exceptions::AttributeError>(self.py()) {
if err.is_instance::<exceptions::PyAttributeError>(self.py()) {
let l = PyList::empty(self.py());
self.setattr("__all__", l).map_err(PyErr::from)?;
Ok(l)
@ -101,7 +101,7 @@ impl PyModule {
match str::from_utf8(slice) {
Ok(s) => Ok(s),
Err(e) => Err(PyErr::from_instance(
exceptions::UnicodeDecodeError::new_utf8(self.py(), slice, e)?,
exceptions::PyUnicodeDecodeError::new_utf8(self.py(), slice, e)?,
)),
}
}

View File

@ -40,7 +40,7 @@ macro_rules! int_fits_larger_int {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let val: $larger_type = obj.extract()?;
<$rust_type>::try_from(val)
.map_err(|e| exceptions::OverflowError::py_err(e.to_string()))
.map_err(|e| exceptions::PyOverflowError::py_err(e.to_string()))
}
}
};
@ -145,7 +145,7 @@ macro_rules! int_fits_c_long {
}
}?;
<$rust_type>::try_from(val)
.map_err(|e| exceptions::OverflowError::py_err(e.to_string()))
.map_err(|e| exceptions::PyOverflowError::py_err(e.to_string()))
}
}
};
@ -551,7 +551,7 @@ mod test {
);
let obj = PyObject::from_owned_ptr_or_panic(py, obj);
let err = obj.extract::<u128>(py).unwrap_err();
assert!(err.is_instance::<exceptions::OverflowError>(py));
assert!(err.is_instance::<exceptions::PyOverflowError>(py));
}
}
@ -569,7 +569,7 @@ mod test {
let obj = ("123").to_object(py);
let err = obj.extract::<$t>(py).unwrap_err();
assert!(err.is_instance::<exceptions::TypeError>(py));
assert!(err.is_instance::<exceptions::PyTypeError>(py));
}
#[test]
@ -579,7 +579,7 @@ mod test {
let obj = (12.3).to_object(py);
let err = obj.extract::<$t>(py).unwrap_err();
assert!(err.is_instance::<exceptions::TypeError>(py));
assert!(err.is_instance::<exceptions::PyTypeError>(py));
}
#[test]

View File

@ -361,7 +361,7 @@ where
{
let seq = <PySequence as PyTryFrom>::try_from(obj)?;
if seq.len()? as usize != slice.len() {
return Err(exceptions::BufferError::py_err(
return Err(exceptions::PyBufferError::py_err(
"Slice length does not match buffer length.",
));
}

View File

@ -141,7 +141,7 @@ fn wrong_tuple_length(t: &PyTuple, expected_length: usize) -> PyErr {
expected_length,
t.len()
);
exceptions::ValueError::py_err(msg)
exceptions::PyValueError::py_err(msg)
}
macro_rules! tuple_conversion ({$length:expr,$(($refN:ident, $n:tt, $T:ident)),+} => {

View File

@ -404,22 +404,22 @@ fn rich_comparisons_python_3_type_error() {
let py = gil.python();
let c2 = PyCell::new(py, RichComparisons2 {}).unwrap();
py_expect_exception!(py, c2, "c2 < c2", TypeError);
py_expect_exception!(py, c2, "c2 < 1", TypeError);
py_expect_exception!(py, c2, "1 < c2", TypeError);
py_expect_exception!(py, c2, "c2 <= c2", TypeError);
py_expect_exception!(py, c2, "c2 <= 1", TypeError);
py_expect_exception!(py, c2, "1 <= c2", TypeError);
py_expect_exception!(py, c2, "c2 < c2", PyTypeError);
py_expect_exception!(py, c2, "c2 < 1", PyTypeError);
py_expect_exception!(py, c2, "1 < c2", PyTypeError);
py_expect_exception!(py, c2, "c2 <= c2", PyTypeError);
py_expect_exception!(py, c2, "c2 <= 1", PyTypeError);
py_expect_exception!(py, c2, "1 <= c2", PyTypeError);
py_run!(py, c2, "assert (c2 == c2) == True");
py_run!(py, c2, "assert (c2 == 1) == True");
py_run!(py, c2, "assert (1 == c2) == True");
py_run!(py, c2, "assert (c2 != c2) == False");
py_run!(py, c2, "assert (c2 != 1) == False");
py_run!(py, c2, "assert (1 != c2) == False");
py_expect_exception!(py, c2, "c2 > c2", TypeError);
py_expect_exception!(py, c2, "c2 > 1", TypeError);
py_expect_exception!(py, c2, "1 > c2", TypeError);
py_expect_exception!(py, c2, "c2 >= c2", TypeError);
py_expect_exception!(py, c2, "c2 >= 1", TypeError);
py_expect_exception!(py, c2, "1 >= c2", TypeError);
py_expect_exception!(py, c2, "c2 > c2", PyTypeError);
py_expect_exception!(py, c2, "c2 > 1", PyTypeError);
py_expect_exception!(py, c2, "1 > c2", PyTypeError);
py_expect_exception!(py, c2, "c2 >= c2", PyTypeError);
py_expect_exception!(py, c2, "c2 >= 1", PyTypeError);
py_expect_exception!(py, c2, "1 >= c2", PyTypeError);
}

View File

@ -1,6 +1,6 @@
use pyo3::buffer::PyBuffer;
use pyo3::class::PyBufferProtocol;
use pyo3::exceptions::BufferError;
use pyo3::exceptions::PyBufferError;
use pyo3::ffi;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
@ -21,11 +21,11 @@ struct TestBufferClass {
impl PyBufferProtocol for TestBufferClass {
fn bf_getbuffer(slf: PyRefMut<Self>, view: *mut ffi::Py_buffer, flags: c_int) -> PyResult<()> {
if view.is_null() {
return Err(BufferError::py_err("View is null"));
return Err(PyBufferError::py_err("View is null"));
}
if (flags & ffi::PyBUF_WRITABLE) == ffi::PyBUF_WRITABLE {
return Err(BufferError::py_err("Object is not writable"));
return Err(PyBufferError::py_err("Object is not writable"));
}
unsafe {

View File

@ -56,7 +56,7 @@ fn class_attributes_are_immutable() {
let gil = Python::acquire_gil();
let py = gil.python();
let foo_obj = py.get_type::<Foo>();
py_expect_exception!(py, foo_obj, "foo_obj.a = 6", TypeError);
py_expect_exception!(py, foo_obj, "foo_obj.a = 6", PyTypeError);
}
#[pymethods]

View File

@ -2,7 +2,7 @@ use pyo3::class::{
PyAsyncProtocol, PyContextProtocol, PyDescrProtocol, PyIterProtocol, PyMappingProtocol,
PyObjectProtocol, PySequenceProtocol,
};
use pyo3::exceptions::{IndexError, ValueError};
use pyo3::exceptions::{PyIndexError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyBytes, PySlice, PyType};
use pyo3::{ffi, py_run, AsPyPointer, PyCell};
@ -42,7 +42,7 @@ fn len() {
},
)
.unwrap();
py_expect_exception!(py, inst, "len(inst)", OverflowError);
py_expect_exception!(py, inst, "len(inst)", PyOverflowError);
}
#[pyclass]
@ -171,7 +171,7 @@ impl PySequenceProtocol for Sequence {
if let Some(s) = self.fields.get(idx) {
Ok(s.clone())
} else {
Err(PyErr::new::<IndexError, _>(()))
Err(PyErr::new::<PyIndexError, _>(()))
}
}
@ -181,7 +181,7 @@ impl PySequenceProtocol for Sequence {
*elem = value;
Ok(())
} else {
Err(PyErr::new::<IndexError, _>(()))
Err(PyErr::new::<PyIndexError, _>(()))
}
}
}
@ -202,7 +202,7 @@ fn sequence() {
assert c[0] == 'H'
"#
);
py_expect_exception!(py, c, "c['abc']", TypeError);
py_expect_exception!(py, c, "c['abc']", PyTypeError);
}
#[pyclass]
@ -256,7 +256,7 @@ fn setitem() {
assert_eq!(c.key, 1);
assert_eq!(c.val, 2);
}
py_expect_exception!(py, c, "del c[1]", NotImplementedError);
py_expect_exception!(py, c, "del c[1]", PyNotImplementedError);
}
#[pyclass]
@ -282,7 +282,7 @@ fn delitem() {
let c = c.borrow();
assert_eq!(c.key, 1);
}
py_expect_exception!(py, c, "c[1] = 2", NotImplementedError);
py_expect_exception!(py, c, "c[1] = 2", PyNotImplementedError);
}
#[pyclass]
@ -354,7 +354,7 @@ fn contains() {
let c = Py::new(py, Contains {}).unwrap();
py_run!(py, c, "assert 1 in c");
py_run!(py, c, "assert -1 not in c");
py_expect_exception!(py, c, "assert 'wrong type' not in c", TypeError);
py_expect_exception!(py, c, "assert 'wrong type' not in c", PyTypeError);
}
#[pyclass]
@ -376,7 +376,7 @@ impl<'p> PyContextProtocol<'p> for ContextManager {
) -> bool {
let gil = GILGuard::acquire();
self.exit_called = true;
ty == Some(gil.python().get_type::<ValueError>())
ty == Some(gil.python().get_type::<PyValueError>())
}
}
@ -402,7 +402,7 @@ fn context_manager() {
py,
c,
"with c as x: raise NotImplementedError",
NotImplementedError
PyNotImplementedError
);
let c = c.borrow();
assert!(c.exit_called);
@ -438,7 +438,7 @@ impl<'p> PyMappingProtocol<'p> for Test {
return Ok("int".into_py(gil.python()));
}
}
Err(PyErr::new::<ValueError, _>("error"))
Err(PyErr::new::<PyValueError, _>("error"))
}
}

View File

@ -46,7 +46,7 @@ impl fmt::Display for CustomError {
impl std::convert::From<CustomError> for PyErr {
fn from(err: CustomError) -> PyErr {
exceptions::OSError::py_err(err.to_string())
exceptions::PyOSError::py_err(err.to_string())
}
}

View File

@ -100,7 +100,10 @@ fn mutation_fails() {
let e = py
.run("obj.base_set(lambda: obj.sub_set_and_ret(1))", global, None)
.unwrap_err();
assert_eq!(&e.instance(py).to_string(), "RuntimeError: Already borrowed")
assert_eq!(
&e.instance(py).to_string(),
"RuntimeError: Already borrowed"
)
}
#[pyclass]

View File

@ -1,6 +1,6 @@
use std::collections::HashMap;
use pyo3::exceptions::KeyError;
use pyo3::exceptions::PyKeyError;
use pyo3::prelude::*;
use pyo3::types::IntoPyDict;
use pyo3::types::PyList;
@ -40,7 +40,7 @@ impl PyMappingProtocol for Mapping {
self.index
.get(&query)
.copied()
.ok_or_else(|| KeyError::py_err("unknown key"))
.ok_or_else(|| PyKeyError::py_err("unknown key"))
}
fn __setitem__(&mut self, key: String, value: usize) {
@ -49,7 +49,7 @@ impl PyMappingProtocol for Mapping {
fn __delitem__(&mut self, key: String) -> PyResult<()> {
if self.index.remove(&key).is_none() {
KeyError::py_err("unknown key").into()
PyKeyError::py_err("unknown key").into()
} else {
Ok(())
}

View File

@ -273,7 +273,7 @@ fn meth_args() {
py_run!(py, inst, "assert inst.get_default() == 10");
py_run!(py, inst, "assert inst.get_default(100) == 100");
py_run!(py, inst, "assert inst.get_kwarg() == 10");
py_expect_exception!(py, inst, "inst.get_kwarg(100)", TypeError);
py_expect_exception!(py, inst, "inst.get_kwarg(100)", PyTypeError);
py_run!(py, inst, "assert inst.get_kwarg(test=100) == 100");
py_run!(py, inst, "assert inst.get_kwargs() == [(), None]");
py_run!(py, inst, "assert inst.get_kwargs(1,2,3) == [(1,2,3), None]");
@ -300,9 +300,9 @@ fn meth_args() {
"assert inst.get_pos_arg_kw(1, b=2) == [1, (), {'b': 2}]"
);
py_run!(py, inst, "assert inst.get_pos_arg_kw(a=1) == [1, (), None]");
py_expect_exception!(py, inst, "inst.get_pos_arg_kw()", TypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw(1, a=1)", TypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw(b=2)", TypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw()", PyTypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw(1, a=1)", PyTypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw(b=2)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_arg_kw_sep1(1) == 6");
py_run!(py, inst, "assert inst.get_pos_arg_kw_sep1(1, 2) == 6");
@ -311,7 +311,7 @@ fn meth_args() {
inst,
"assert inst.get_pos_arg_kw_sep1(1, 2, c=13) == 16"
);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw_sep1(1, 2, 3)", TypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw_sep1(1, 2, 3)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_arg_kw_sep2(1) == 6");
py_run!(
@ -319,10 +319,10 @@ fn meth_args() {
inst,
"assert inst.get_pos_arg_kw_sep2(1, b=12, c=13) == 26"
);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw_sep2(1, 2)", TypeError);
py_expect_exception!(py, inst, "inst.get_pos_arg_kw_sep2(1, 2)", PyTypeError);
py_run!(py, inst, "assert inst.get_pos_kw(1, b=2) == [1, {'b': 2}]");
py_expect_exception!(py, inst, "inst.get_pos_kw(1,2)", TypeError);
py_expect_exception!(py, inst, "inst.get_pos_kw(1,2)", PyTypeError);
py_run!(py, inst, "assert inst.args_as_vec(1,2,3) == 6");
}

View File

@ -47,7 +47,7 @@ a = array.array("i", [0, 1, 2, 3])
b = array.array("I", [0, 1, 2, 3])
f(a, b)
"#,
BufferError
PyBufferError
);
pyo3::py_run!(

View File

@ -1,5 +1,5 @@
use pyo3::class::PySequenceProtocol;
use pyo3::exceptions::{IndexError, ValueError};
use pyo3::exceptions::{PyIndexError, PyValueError};
use pyo3::prelude::*;
use pyo3::types::{IntoPyDict, PyList};
@ -41,7 +41,7 @@ impl PySequenceProtocol for ByteSequence {
self.elements
.get(idx as usize)
.copied()
.ok_or_else(|| IndexError::py_err("list index out of range"))
.ok_or_else(|| PyIndexError::py_err("list index out of range"))
}
fn __setitem__(&mut self, idx: isize, value: u8) {
@ -53,7 +53,7 @@ impl PySequenceProtocol for ByteSequence {
self.elements.remove(idx as usize);
Ok(())
} else {
Err(IndexError::py_err("list index out of range"))
Err(PyIndexError::py_err("list index out of range"))
}
}
@ -78,7 +78,7 @@ impl PySequenceProtocol for ByteSequence {
}
Ok(Self { elements })
} else {
Err(ValueError::py_err("invalid repeat count"))
Err(PyValueError::py_err("invalid repeat count"))
}
}
}
@ -242,7 +242,7 @@ impl PySequenceProtocol for OptionList {
fn __getitem__(&self, idx: isize) -> PyResult<Option<i64>> {
match self.items.get(idx as usize) {
Some(x) => Ok(*x),
None => Err(PyErr::new::<IndexError, _>("Index out of bounds")),
None => Err(PyIndexError::py_err("Index out of bounds")),
}
}
}
@ -263,5 +263,5 @@ fn test_option_list_get() {
py_assert!(py, list, "list[0] == 1");
py_assert!(py, list, "list[1] == None");
py_expect_exception!(py, list, "list[2]", IndexError);
py_expect_exception!(py, list, "list[2]", PyIndexError);
}