Skip to content

Commit 52779f0

Browse files
committed
Rename PyConcreteException::py_err to new_err
1 parent 80ea2e4 commit 52779f0

22 files changed

+69
-88
lines changed

CHANGELOG.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.
3636
- Change `PyErr::print()` and `PyErr::print_and_set_sys_last_vars()` to take `&self` instead of `self`.
3737
- Remove `PyErr::from_value`, `PyErr::into_normalized()` and `PyErr::normalize()`.
3838
- Change `PyErrValue` to be a private type.
39+
- Remove `PyException::into()` and `Into<PyResult<T>>` for `PyErr` and `PyException`.
40+
- Rename `PyException::py_err()` to `PyException::new_err()`.
41+
- Rename `PyUnicodeDecodeErr::new_err()` to `PyUnicodeDecodeErr::new()`.
3942

4043

4144
### Removed

guide/src/exception.md

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,7 @@ If you already have a Python exception instance, you can simply call [`PyErr::fr
7676
PyErr::from_instance(py, err).restore(py);
7777
```
7878

79-
If a Rust type exists for the exception, then it is possible to use the `py_err` method.
79+
If a Rust type exists for the exception, then it is possible to use the `new_err` method.
8080
For example, each standard exception defined in the `pyo3::exceptions` module
8181
has a corresponding Rust type, exceptions defined by [`create_exception!`] and [`import_exception!`] macro
8282
have Rust types as well.
@@ -87,7 +87,7 @@ have Rust types as well.
8787
# fn check_for_error() -> bool {false}
8888
fn my_func(arg: PyObject) -> PyResult<()> {
8989
if check_for_error() {
90-
Err(PyValueError::py_err("argument is wrong"))
90+
Err(PyValueError::new_err("argument is wrong"))
9191
} else {
9292
Ok(())
9393
}
@@ -123,7 +123,7 @@ To check the type of an exception, you can simply do:
123123
# fn main() {
124124
# let gil = Python::acquire_gil();
125125
# let py = gil.python();
126-
# let err = PyTypeError::py_err(());
126+
# let err = PyTypeError::new_err(());
127127
err.is_instance::<PyTypeError>(py);
128128
# }
129129
```
@@ -170,7 +170,7 @@ until a `Python` object is available.
170170
# }
171171
impl std::convert::From<CustomIOError> for PyErr {
172172
fn from(err: CustomIOError) -> PyErr {
173-
PyOSError::py_err(err.to_string())
173+
PyOSError::new_err(err.to_string())
174174
}
175175
}
176176

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

215215
match file.call_method0("tell") {
216-
Err(_) => Err(io::UnsupportedOperation::py_err("not supported: tell")),
216+
Err(_) => Err(io::UnsupportedOperation::new_err("not supported: tell")),
217217
Ok(x) => x.extract::<u64>(),
218218
}
219219
}

src/buffer.rs

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -156,10 +156,10 @@ pub unsafe trait Element: Copy {
156156
fn validate(b: &ffi::Py_buffer) -> PyResult<()> {
157157
// shape and stride information must be provided when we use PyBUF_FULL_RO
158158
if b.shape.is_null() {
159-
return Err(exceptions::PyBufferError::py_err("Shape is Null"));
159+
return Err(exceptions::PyBufferError::new_err("Shape is Null"));
160160
}
161161
if b.strides.is_null() {
162-
return Err(exceptions::PyBufferError::py_err(
162+
return Err(exceptions::PyBufferError::new_err(
163163
"PyBuffer: Strides is Null",
164164
));
165165
}
@@ -190,7 +190,7 @@ impl<T: Element> PyBuffer<T> {
190190
{
191191
Ok(buf)
192192
} else {
193-
Err(exceptions::PyBufferError::py_err(
193+
Err(exceptions::PyBufferError::new_err(
194194
"Incompatible type as buffer",
195195
))
196196
}
@@ -441,7 +441,7 @@ impl<T: Element> PyBuffer<T> {
441441

442442
fn copy_to_slice_impl(&self, py: Python, target: &mut [T], fort: u8) -> PyResult<()> {
443443
if mem::size_of_val(target) != self.len_bytes() {
444-
return Err(exceptions::PyBufferError::py_err(
444+
return Err(exceptions::PyBufferError::new_err(
445445
"Slice length does not match buffer length.",
446446
));
447447
}
@@ -528,7 +528,7 @@ impl<T: Element> PyBuffer<T> {
528528
return buffer_readonly_error();
529529
}
530530
if mem::size_of_val(source) != self.len_bytes() {
531-
return Err(exceptions::PyBufferError::py_err(
531+
return Err(exceptions::PyBufferError::new_err(
532532
"Slice length does not match buffer length.",
533533
));
534534
}
@@ -564,7 +564,7 @@ impl<T: Element> PyBuffer<T> {
564564

565565
#[inline(always)]
566566
fn buffer_readonly_error() -> PyResult<()> {
567-
Err(exceptions::PyBufferError::py_err(
567+
Err(exceptions::PyBufferError::new_err(
568568
"Cannot write to read-only buffer.",
569569
))
570570
}

src/callback.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ impl IntoPyCallbackOutput<ffi::Py_ssize_t> for usize {
8686
if self <= (isize::MAX as usize) {
8787
Ok(self as isize)
8888
} else {
89-
Err(PyOverflowError::py_err(()))
89+
Err(PyOverflowError::new_err(()))
9090
}
9191
}
9292
}
@@ -244,11 +244,11 @@ macro_rules! callback_body_without_convert {
244244
Err(e) => {
245245
// Try to format the error in the same way panic does
246246
if let Some(string) = e.downcast_ref::<String>() {
247-
Err($crate::panic::PanicException::py_err((string.clone(),)))
247+
Err($crate::panic::PanicException::new_err((string.clone(),)))
248248
} else if let Some(s) = e.downcast_ref::<&str>() {
249-
Err($crate::panic::PanicException::py_err((s.to_string(),)))
249+
Err($crate::panic::PanicException::new_err((s.to_string(),)))
250250
} else {
251-
Err($crate::panic::PanicException::py_err((
251+
Err($crate::panic::PanicException::new_err((
252252
"panic from Rust code",
253253
)))
254254
}

src/class/iter.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -112,7 +112,7 @@ impl IntoPyCallbackOutput<*mut ffi::PyObject> for PyIterNextOutput {
112112
fn convert(self, _py: Python) -> PyResult<*mut ffi::PyObject> {
113113
match self {
114114
IterNextOutput::Yield(o) => Ok(o.into_ptr()),
115-
IterNextOutput::Return(opt) => Err(crate::exceptions::PyStopIteration::py_err((opt,))),
115+
IterNextOutput::Return(opt) => Err(crate::exceptions::PyStopIteration::new_err((opt,))),
116116
}
117117
}
118118
}

src/class/pyasync.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ impl IntoPyCallbackOutput<*mut ffi::PyObject> for PyIterANextOutput {
119119
match self {
120120
IterANextOutput::Yield(o) => Ok(o.into_ptr()),
121121
IterANextOutput::Return(opt) => {
122-
Err(crate::exceptions::PyStopAsyncIteration::py_err((opt,)))
122+
Err(crate::exceptions::PyStopAsyncIteration::new_err((opt,)))
123123
}
124124
}
125125
}

src/derive_utils.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -43,7 +43,7 @@ pub fn parse_fn_args<'p>(
4343
let nargs = args.len();
4444
let mut used_args = 0;
4545
macro_rules! raise_error {
46-
($s: expr $(,$arg:expr)*) => (return Err(PyTypeError::py_err(format!(
46+
($s: expr $(,$arg:expr)*) => (return Err(PyTypeError::new_err(format!(
4747
concat!("{} ", $s), fname.unwrap_or("function") $(,$arg)*
4848
))))
4949
}

src/err/mod.rs

Lines changed: 8 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,7 @@ impl PyErr {
7979
/// In most cases, you can use a concrete exception's constructors instead:
8080
/// the example is equivalent to
8181
/// ```ignore
82-
/// return Err(exceptions::PyTypeError::py_err("Error message"));
82+
/// return Err(exceptions::PyTypeError::new_err("Error message"));
8383
/// return exceptions::PyTypeError::into("Error message");
8484
/// ```
8585
pub fn new<T, V>(value: V) -> PyErr
@@ -174,7 +174,7 @@ impl PyErr {
174174
/// ```rust
175175
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
176176
/// Python::with_gil(|py| {
177-
/// let err = PyTypeError::py_err(("some type error",));
177+
/// let err = PyTypeError::new_err(("some type error",));
178178
/// assert_eq!(err.ptype(py), PyType::new::<PyTypeError>(py));
179179
/// });
180180
/// ```
@@ -190,7 +190,7 @@ impl PyErr {
190190
/// ```rust
191191
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
192192
/// Python::with_gil(|py| {
193-
/// let err = PyTypeError::py_err(("some type error",));
193+
/// let err = PyTypeError::new_err(("some type error",));
194194
/// assert_eq!(err.pvalue(py).to_string(), "TypeError: some type error");
195195
/// });
196196
/// ```
@@ -206,7 +206,7 @@ impl PyErr {
206206
/// ```rust
207207
/// use pyo3::{Python, PyErr, exceptions::PyTypeError, types::PyType};
208208
/// Python::with_gil(|py| {
209-
/// let err = PyTypeError::py_err(("some type error",));
209+
/// let err = PyTypeError::new_err(("some type error",));
210210
/// assert_eq!(err.ptraceback(py), None);
211211
/// });
212212
/// ```
@@ -426,7 +426,7 @@ impl PyErr {
426426
ptype: Py::from_owned_ptr_or_opt(py, ptype)
427427
.unwrap_or_else(|| exceptions::PySystemError::type_object(py).into()),
428428
pvalue: Py::from_owned_ptr_or_opt(py, pvalue).unwrap_or_else(|| {
429-
exceptions::PySystemError::py_err("Exception value missing")
429+
exceptions::PySystemError::new_err("Exception value missing")
430430
.instance(py)
431431
.into_py(py)
432432
}),
@@ -476,7 +476,7 @@ impl<'a> IntoPy<PyObject> for &'a PyErr {
476476
/// Convert `PyDowncastError` to Python `TypeError`.
477477
impl<'a> std::convert::From<PyDowncastError<'a>> for PyErr {
478478
fn from(err: PyDowncastError) -> PyErr {
479-
exceptions::PyTypeError::py_err(err.to_string())
479+
exceptions::PyTypeError::new_err(err.to_string())
480480
}
481481
}
482482

@@ -496,13 +496,6 @@ impl<'a> std::fmt::Display for PyDowncastError<'a> {
496496
}
497497
}
498498

499-
/// Convert `PyErr` to `PyResult<T>`
500-
impl<T> std::convert::Into<PyResult<T>> for PyErr {
501-
fn into(self) -> PyResult<T> {
502-
Err(self)
503-
}
504-
}
505-
506499
pub fn panic_after_error(_py: Python) -> ! {
507500
unsafe {
508501
ffi::PyErr_Print();
@@ -531,7 +524,7 @@ mod tests {
531524
fn set_typeerror() {
532525
let gil = Python::acquire_gil();
533526
let py = gil.python();
534-
let err: PyErr = exceptions::PyTypeError::py_err(());
527+
let err: PyErr = exceptions::PyTypeError::new_err(());
535528
err.restore(py);
536529
assert!(PyErr::occurred(py));
537530
drop(PyErr::fetch(py));
@@ -549,7 +542,7 @@ mod tests {
549542

550543
let gil = Python::acquire_gil();
551544
let py = gil.python();
552-
let err: PyErr = PanicException::py_err("new panic");
545+
let err: PyErr = PanicException::new_err("new panic");
553546
err.restore(py);
554547
assert!(PyErr::occurred(py));
555548
let started_unwind =

src/exceptions.rs

Lines changed: 20 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
//! Exception types defined by Python.
44
55
use crate::type_object::PySizedLayout;
6-
use crate::types::{PyAny, PyTuple};
6+
use crate::types::PyTuple;
77
use crate::{ffi, AsPyPointer, PyResult, Python};
88
use std::ffi::CStr;
99
use std::ops;
@@ -19,20 +19,11 @@ macro_rules! impl_exception_boilerplate {
1919
}
2020
}
2121

22-
impl<T> std::convert::Into<$crate::PyResult<T>> for $name {
23-
fn into(self) -> $crate::PyResult<T> {
24-
$crate::PyErr::new::<$name, _>(()).into()
25-
}
26-
}
27-
2822
impl $name {
29-
pub fn py_err<V: $crate::ToPyObject + Send + Sync + 'static>(args: V) -> $crate::PyErr {
30-
$crate::PyErr::new::<$name, V>(args)
31-
}
32-
pub fn into<R, V: $crate::ToPyObject + Send + Sync + 'static>(
23+
pub fn new_err<V: $crate::ToPyObject + Send + Sync + 'static>(
3324
args: V,
34-
) -> $crate::PyResult<R> {
35-
$crate::PyErr::new::<$name, V>(args).into()
25+
) -> $crate::PyErr {
26+
$crate::PyErr::new::<$name, V>(args)
3627
}
3728
}
3829

@@ -451,13 +442,13 @@ impl_native_exception!(PyIOError, IOError, PyExc_IOError);
451442
impl_native_exception!(PyWindowsError, WindowsError, PyExc_WindowsError);
452443

453444
impl PyUnicodeDecodeError {
454-
pub fn new_err<'p>(
445+
pub fn new<'p>(
455446
py: Python<'p>,
456447
encoding: &CStr,
457448
input: &[u8],
458449
range: ops::Range<usize>,
459450
reason: &CStr,
460-
) -> PyResult<&'p PyAny> {
451+
) -> PyResult<&'p PyUnicodeDecodeError> {
461452
unsafe {
462453
let input: &[c_char] = &*(input as *const [u8] as *const [c_char]);
463454
py.from_owned_ptr_or_err(ffi::PyUnicodeDecodeError_Create(
@@ -476,9 +467,9 @@ impl PyUnicodeDecodeError {
476467
py: Python<'p>,
477468
input: &[u8],
478469
err: std::str::Utf8Error,
479-
) -> PyResult<&'p PyAny> {
470+
) -> PyResult<&'p PyUnicodeDecodeError> {
480471
let pos = err.valid_up_to();
481-
PyUnicodeDecodeError::new_err(
472+
PyUnicodeDecodeError::new(
482473
py,
483474
CStr::from_bytes_with_nul(b"utf-8\0").unwrap(),
484475
input,
@@ -523,7 +514,6 @@ mod test {
523514
use crate::types::{IntoPyDict, PyDict};
524515
use crate::{PyErr, Python};
525516
use std::error::Error;
526-
use std::fmt::Write;
527517

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

536-
let err: PyErr = gaierror::py_err(());
526+
let err: PyErr = gaierror::new_err(());
537527
let socket = py
538528
.import("socket")
539529
.map_err(|e| e.print(py))
@@ -558,7 +548,7 @@ mod test {
558548
let gil = Python::acquire_gil();
559549
let py = gil.python();
560550

561-
let err: PyErr = MessageError::py_err(());
551+
let err: PyErr = MessageError::new_err(());
562552
let email = py
563553
.import("email")
564554
.map_err(|e| e.print(py))
@@ -605,35 +595,30 @@ mod test {
605595

606596
#[test]
607597
fn native_exception_display() {
608-
let mut out = String::new();
609598
let gil = Python::acquire_gil();
610599
let py = gil.python();
611-
let err = py
600+
let exc = py
612601
.run("raise Exception('banana')", None, None)
613-
.expect_err("raising should have given us an error");
614-
write!(&mut out, "{}", err.instance(py)).expect("successful format");
615-
assert_eq!(out, "Exception: banana");
602+
.expect_err("raising should have given us an error")
603+
.into_instance(py);
604+
assert_eq!(exc.to_string(), "Exception: banana");
616605
}
617606

618607
#[test]
619608
fn native_exception_chain() {
620-
let mut out = String::new();
621609
let gil = Python::acquire_gil();
622610
let py = gil.python();
623-
let err = py
611+
let exc = py
624612
.run(
625613
"raise Exception('banana') from TypeError('peach')",
626614
None,
627615
None,
628616
)
629-
.expect_err("raising should have given us an error");
630-
let instance = err.instance(py);
631-
write!(&mut out, "{}", instance).expect("successful format");
632-
assert_eq!(out, "Exception: banana");
633-
out.clear();
634-
let source = instance.source().expect("cause should exist");
635-
write!(&mut out, "{}", source).expect("successful format");
636-
assert_eq!(out, "TypeError: peach");
617+
.expect_err("raising should have given us an error")
618+
.into_instance(py);
619+
assert_eq!(exc.to_string(), "Exception: banana");
620+
let source = exc.as_ref(py).source().expect("cause should exist");
621+
assert_eq!(source.to_string(), "TypeError: peach");
637622
let source_source = source.source();
638623
assert!(source_source.is_none(), "source_source should be None");
639624
}

src/pycell.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -730,7 +730,7 @@ impl fmt::Display for PyBorrowError {
730730

731731
impl From<PyBorrowError> for PyErr {
732732
fn from(other: PyBorrowError) -> Self {
733-
PyRuntimeError::py_err(other.to_string())
733+
PyRuntimeError::new_err(other.to_string())
734734
}
735735
}
736736

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

756756
impl From<PyBorrowMutError> for PyErr {
757757
fn from(other: PyBorrowMutError) -> Self {
758-
PyRuntimeError::py_err(other.to_string())
758+
PyRuntimeError::new_err(other.to_string())
759759
}
760760
}

0 commit comments

Comments
 (0)