Merge pull request #1988 from davidhewitt/tidy-fetch-take

err: tidy up some uses of PyErr::occurred
This commit is contained in:
David Hewitt 2021-11-12 22:16:38 +00:00 committed by GitHub
commit 14269d538e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 21 additions and 23 deletions

View File

@ -52,11 +52,13 @@ impl<'source> FromPyObject<'source> for f64 {
fn extract(obj: &'source PyAny) -> PyResult<Self> {
let v = unsafe { ffi::PyFloat_AsDouble(obj.as_ptr()) };
if v == -1.0 && PyErr::occurred(obj.py()) {
Err(PyErr::fetch(obj.py()))
} else {
Ok(v)
if v == -1.0 {
if let Some(err) = PyErr::take(obj.py()) {
return Err(err);
}
}
Ok(v)
}
}

View File

@ -58,13 +58,7 @@ impl<'p> Iterator for &'p PyIterator {
match unsafe { py.from_owned_ptr_or_opt(ffi::PyIter_Next(self.0.as_ptr())) } {
Some(obj) => Some(Ok(obj)),
None => {
if PyErr::occurred(py) {
Some(Err(PyErr::fetch(py)))
} else {
None
}
}
None => PyErr::take(py).map(Err),
}
}
}

View File

@ -10,18 +10,6 @@ use std::convert::TryFrom;
use std::i64;
use std::os::raw::c_long;
fn err_if_invalid_value<T: PartialEq>(
py: Python,
invalid_value: T,
actual_value: T,
) -> PyResult<T> {
if actual_value == invalid_value && PyErr::occurred(py) {
Err(PyErr::fetch(py))
} else {
Ok(actual_value)
}
}
macro_rules! int_fits_larger_int {
($rust_type:ty, $larger_type:ty) => {
impl ToPyObject for $rust_type {
@ -273,6 +261,20 @@ mod slow_128bit_int_conversion {
int_convert_128!(u128, u64);
}
fn err_if_invalid_value<T: PartialEq>(
py: Python,
invalid_value: T,
actual_value: T,
) -> PyResult<T> {
if actual_value == invalid_value {
if let Some(err) = PyErr::take(py) {
return Err(err);
}
}
Ok(actual_value)
}
#[cfg(test)]
mod test_128bit_intergers {
use super::*;