pub struct PyErr { /* private fields */ }
Expand description
Represents a Python exception.
To avoid needing access to Python
in Into
conversions to create PyErr
(thus improving
compatibility with ?
and other Rust errors) this type supports creating exceptions instances
in a lazy fashion, where the full Python object for the exception is created only when needed.
Accessing the contained exception in any way, such as with value_bound
,
get_type_bound
, or is_instance_bound
will create the full exception object if it was not already created.
Implementations§
Source§impl PyErr
impl PyErr
Sourcepub fn new<T, A>(args: A) -> PyErr
pub fn new<T, A>(args: A) -> PyErr
Creates a new PyErr of type T
.
args
can be:
- a tuple: the exception instance will be created using the equivalent to the Python
expression
T(*tuple)
- any other value: the exception instance will be created using the equivalent to the Python
expression
T(value)
This exception instance will be initialized lazily. This avoids the need for the Python GIL
to be held, but requires args
to be Send
and Sync
. If args
is not Send
or Sync
,
consider using PyErr::from_value_bound
instead.
If T
does not inherit from BaseException
, then a TypeError
will be returned.
If calling T’s constructor with args
raises an exception, that exception will be returned.
§Examples
use pyo3::prelude::*;
use pyo3::exceptions::PyTypeError;
#[pyfunction]
fn always_throws() -> PyResult<()> {
Err(PyErr::new::<PyTypeError, _>("Error message"))
}
In most cases, you can use a concrete exception’s constructor instead:
use pyo3::prelude::*;
use pyo3::exceptions::PyTypeError;
#[pyfunction]
fn always_throws() -> PyResult<()> {
Err(PyTypeError::new_err("Error message"))
}
Sourcepub fn from_type<A>(ty: Bound<'_, PyType>, args: A) -> PyErr
pub fn from_type<A>(ty: Bound<'_, PyType>, args: A) -> PyErr
Constructs a new PyErr from the given Python type and arguments.
ty
is the exception type; usually one of the standard exceptions
like exceptions::PyRuntimeError
.
args
is either a tuple or a single value, with the same meaning as in PyErr::new
.
If ty
does not inherit from BaseException
, then a TypeError
will be returned.
If calling ty
with args
raises an exception, that exception will be returned.
Sourcepub fn from_type_bound<A>(ty: Bound<'_, PyType>, args: A) -> PyErr
👎Deprecated since 0.23.0: renamed to PyErr::from_type
pub fn from_type_bound<A>(ty: Bound<'_, PyType>, args: A) -> PyErr
PyErr::from_type
Deprecated name for PyErr::from_type
.
Sourcepub fn from_value(obj: Bound<'_, PyAny>) -> PyErr
pub fn from_value(obj: Bound<'_, PyAny>) -> PyErr
Creates a new PyErr.
If obj
is a Python exception object, the PyErr will contain that object.
If obj
is a Python exception type object, this is equivalent to PyErr::from_type(obj, ())
.
Otherwise, a TypeError
is created.
§Examples
use pyo3::prelude::*;
use pyo3::PyTypeInfo;
use pyo3::exceptions::PyTypeError;
use pyo3::types::PyString;
Python::with_gil(|py| {
// Case #1: Exception object
let err = PyErr::from_value(PyTypeError::new_err("some type error")
.value(py).clone().into_any());
assert_eq!(err.to_string(), "TypeError: some type error");
// Case #2: Exception type
let err = PyErr::from_value(PyTypeError::type_object(py).into_any());
assert_eq!(err.to_string(), "TypeError: ");
// Case #3: Invalid exception value
let err = PyErr::from_value(PyString::new(py, "foo").into_any());
assert_eq!(
err.to_string(),
"TypeError: exceptions must derive from BaseException"
);
});
Sourcepub fn from_value_bound(obj: Bound<'_, PyAny>) -> PyErr
👎Deprecated since 0.23.0: renamed to PyErr::from_value
pub fn from_value_bound(obj: Bound<'_, PyAny>) -> PyErr
PyErr::from_value
Deprecated name for PyErr::from_value
.
Sourcepub fn get_type<'py>(&self, py: Python<'py>) -> Bound<'py, PyType>
pub fn get_type<'py>(&self, py: Python<'py>) -> Bound<'py, PyType>
Returns the type of this exception.
§Examples
use pyo3::{prelude::*, exceptions::PyTypeError, types::PyType};
Python::with_gil(|py| {
let err: PyErr = PyTypeError::new_err(("some type error",));
assert!(err.get_type(py).is(&PyType::new::<PyTypeError>(py)));
});
Sourcepub fn get_type_bound<'py>(&self, py: Python<'py>) -> Bound<'py, PyType>
👎Deprecated since 0.23.0: renamed to PyErr::get_type
pub fn get_type_bound<'py>(&self, py: Python<'py>) -> Bound<'py, PyType>
PyErr::get_type
Deprecated name for PyErr::get_type
.
Sourcepub fn value<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException>
pub fn value<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException>
Returns the value of this exception.
§Examples
use pyo3::{exceptions::PyTypeError, PyErr, Python};
Python::with_gil(|py| {
let err: PyErr = PyTypeError::new_err(("some type error",));
assert!(err.is_instance_of::<PyTypeError>(py));
assert_eq!(err.value(py).to_string(), "some type error");
});
Sourcepub fn value_bound<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException>
👎Deprecated since 0.23.0: renamed to PyErr::value
pub fn value_bound<'py>(&self, py: Python<'py>) -> &Bound<'py, PyBaseException>
PyErr::value
Deprecated name for PyErr::value
.
Sourcepub fn into_value(self, py: Python<'_>) -> Py<PyBaseException>
pub fn into_value(self, py: Python<'_>) -> Py<PyBaseException>
Consumes self to take ownership of the exception value contained in this error.
Sourcepub fn traceback<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>>
pub fn traceback<'py>(&self, py: Python<'py>) -> Option<Bound<'py, PyTraceback>>
Returns the traceback of this exception object.
§Examples
use pyo3::{exceptions::PyTypeError, Python};
Python::with_gil(|py| {
let err = PyTypeError::new_err(("some type error",));
assert!(err.traceback(py).is_none());
});
Sourcepub fn traceback_bound<'py>(
&self,
py: Python<'py>,
) -> Option<Bound<'py, PyTraceback>>
👎Deprecated since 0.23.0: renamed to PyErr::traceback
pub fn traceback_bound<'py>( &self, py: Python<'py>, ) -> Option<Bound<'py, PyTraceback>>
PyErr::traceback
Deprecated name for PyErr::traceback
.
Sourcepub fn occurred(_: Python<'_>) -> bool
pub fn occurred(_: Python<'_>) -> bool
Gets whether an error is present in the Python interpreter’s global state.
Sourcepub fn take(py: Python<'_>) -> Option<PyErr>
pub fn take(py: Python<'_>) -> Option<PyErr>
Takes the current error from the Python interpreter’s global state and clears the global
state. If no error is set, returns None
.
If the error is a PanicException
(which would have originated from a panic in a pyo3
callback) then this function will resume the panic.
Use this function when it is not known if an error should be present. If the error is
expected to have been set, for example from PyErr::occurred
or by an error return value
from a C FFI function, use PyErr::fetch
.
Sourcepub fn fetch(py: Python<'_>) -> PyErr
pub fn fetch(py: Python<'_>) -> PyErr
Equivalent to PyErr::take, but when no error is set:
- Panics in debug mode.
- Returns a
SystemError
in release mode.
This behavior is consistent with Python’s internal handling of what happens when a C return value indicates an error occurred but the global error state is empty. (A lack of exception should be treated as a bug in the code which returned an error code but did not set an exception.)
Use this function when the error is expected to have been set, for example from PyErr::occurred or by an error return value from a C FFI function.
Sourcepub fn new_type<'py>(
py: Python<'py>,
name: &CStr,
doc: Option<&CStr>,
base: Option<&Bound<'py, PyType>>,
dict: Option<PyObject>,
) -> PyResult<Py<PyType>>
pub fn new_type<'py>( py: Python<'py>, name: &CStr, doc: Option<&CStr>, base: Option<&Bound<'py, PyType>>, dict: Option<PyObject>, ) -> PyResult<Py<PyType>>
Creates a new exception type with the given name and docstring.
base
can be an existing exception type to subclass, or a tuple of classes.dict
specifies an optional dictionary of class variables and methods.doc
will be the docstring seen by python users.
§Errors
This function returns an error if name
is not of the form <module>.<ExceptionName>
.
Sourcepub fn new_type_bound<'py>(
py: Python<'py>,
name: &str,
doc: Option<&str>,
base: Option<&Bound<'py, PyType>>,
dict: Option<PyObject>,
) -> PyResult<Py<PyType>>
👎Deprecated since 0.23.0: renamed to PyErr::new_type
pub fn new_type_bound<'py>( py: Python<'py>, name: &str, doc: Option<&str>, base: Option<&Bound<'py, PyType>>, dict: Option<PyObject>, ) -> PyResult<Py<PyType>>
PyErr::new_type
Deprecated name for PyErr::new_type
.
Sourcepub fn print(&self, py: Python<'_>)
pub fn print(&self, py: Python<'_>)
Calls sys.excepthook
and then prints a standard traceback to sys.stderr
.
Sourcepub fn print_and_set_sys_last_vars(&self, py: Python<'_>)
pub fn print_and_set_sys_last_vars(&self, py: Python<'_>)
Calls sys.excepthook
and then prints a standard traceback to sys.stderr
.
Additionally sets sys.last_{type,value,traceback,exc}
attributes to this exception.
Sourcepub fn matches<'py, T>(&self, py: Python<'py>, exc: T) -> Result<bool, T::Error>where
T: IntoPyObject<'py>,
pub fn matches<'py, T>(&self, py: Python<'py>, exc: T) -> Result<bool, T::Error>where
T: IntoPyObject<'py>,
Returns true if the current exception matches the exception in exc
.
If exc
is a class object, this also returns true
when self
is an instance of a subclass.
If exc
is a tuple, all exceptions in the tuple (and recursively in subtuples) are searched for a match.
Sourcepub fn is_instance(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool
pub fn is_instance(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool
Returns true if the current exception is instance of T
.
Sourcepub fn is_instance_bound(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool
👎Deprecated since 0.23.0: renamed to PyErr::is_instance
pub fn is_instance_bound(&self, py: Python<'_>, ty: &Bound<'_, PyAny>) -> bool
PyErr::is_instance
Deprecated name for PyErr::is_instance
.
Sourcepub fn is_instance_of<T>(&self, py: Python<'_>) -> boolwhere
T: PyTypeInfo,
pub fn is_instance_of<T>(&self, py: Python<'_>) -> boolwhere
T: PyTypeInfo,
Returns true if the current exception is instance of T
.
Sourcepub fn restore(self, py: Python<'_>)
pub fn restore(self, py: Python<'_>)
Writes the error back to the Python interpreter’s global state.
This is the opposite of PyErr::fetch()
.
Sourcepub fn write_unraisable(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>)
pub fn write_unraisable(self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>)
Reports the error as unraisable.
This calls sys.unraisablehook()
using the current exception and obj argument.
This method is useful to report errors in situations where there is no good mechanism to report back to the Python land. In Python this is used to indicate errors in background threads or destructors which are protected. In Rust code this is commonly useful when you are calling into a Python callback which might fail, but there is no obvious way to handle this error other than logging it.
Calling this method has the benefit that the error goes back into a standardized callback
in Python which for instance allows unittests to ensure that no unraisable error
actually happend by hooking sys.unraisablehook
.
Example:
Python::with_gil(|py| {
match failing_function() {
Err(pyerr) => pyerr.write_unraisable(py, None),
Ok(..) => { /* do something here */ }
}
Ok(())
})
Sourcepub fn write_unraisable_bound(
self,
py: Python<'_>,
obj: Option<&Bound<'_, PyAny>>,
)
👎Deprecated since 0.23.0: renamed to PyErr::write_unraisable
pub fn write_unraisable_bound( self, py: Python<'_>, obj: Option<&Bound<'_, PyAny>>, )
PyErr::write_unraisable
Deprecated name for PyErr::write_unraisable
.
Sourcepub fn warn<'py>(
py: Python<'py>,
category: &Bound<'py, PyAny>,
message: &CStr,
stacklevel: i32,
) -> PyResult<()>
pub fn warn<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &CStr, stacklevel: i32, ) -> PyResult<()>
Issues a warning message.
May return an Err(PyErr)
if warnings-as-errors is enabled.
Equivalent to warnings.warn()
in Python.
The category
should be one of the Warning
classes available in
pyo3::exceptions
, or a subclass. The Python
object can be retrieved using Python::get_type_bound()
.
Example:
Python::with_gil(|py| {
let user_warning = py.get_type::<pyo3::exceptions::PyUserWarning>();
PyErr::warn(py, &user_warning, c_str!("I am warning you"), 0)?;
Ok(())
})
Sourcepub fn warn_bound<'py>(
py: Python<'py>,
category: &Bound<'py, PyAny>,
message: &str,
stacklevel: i32,
) -> PyResult<()>
👎Deprecated since 0.23.0: renamed to PyErr::warn
pub fn warn_bound<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &str, stacklevel: i32, ) -> PyResult<()>
PyErr::warn
Deprecated name for PyErr::warn
.
Sourcepub fn warn_explicit<'py>(
py: Python<'py>,
category: &Bound<'py, PyAny>,
message: &CStr,
filename: &CStr,
lineno: i32,
module: Option<&CStr>,
registry: Option<&Bound<'py, PyAny>>,
) -> PyResult<()>
pub fn warn_explicit<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &CStr, filename: &CStr, lineno: i32, module: Option<&CStr>, registry: Option<&Bound<'py, PyAny>>, ) -> PyResult<()>
Issues a warning message, with more control over the warning attributes.
May return a PyErr
if warnings-as-errors is enabled.
Equivalent to warnings.warn_explicit()
in Python.
The category
should be one of the Warning
classes available in
pyo3::exceptions
, or a subclass.
Sourcepub fn warn_explicit_bound<'py>(
py: Python<'py>,
category: &Bound<'py, PyAny>,
message: &str,
filename: &str,
lineno: i32,
module: Option<&str>,
registry: Option<&Bound<'py, PyAny>>,
) -> PyResult<()>
👎Deprecated since 0.23.0: renamed to PyErr::warn
pub fn warn_explicit_bound<'py>( py: Python<'py>, category: &Bound<'py, PyAny>, message: &str, filename: &str, lineno: i32, module: Option<&str>, registry: Option<&Bound<'py, PyAny>>, ) -> PyResult<()>
PyErr::warn
Deprecated name for PyErr::warn_explicit
.
Sourcepub fn clone_ref(&self, py: Python<'_>) -> PyErr
pub fn clone_ref(&self, py: Python<'_>) -> PyErr
Clone the PyErr. This requires the GIL, which is why PyErr does not implement Clone.
§Examples
use pyo3::{exceptions::PyTypeError, PyErr, Python, prelude::PyAnyMethods};
Python::with_gil(|py| {
let err: PyErr = PyTypeError::new_err(("some type error",));
let err_clone = err.clone_ref(py);
assert!(err.get_type(py).is(&err_clone.get_type(py)));
assert!(err.value(py).is(err_clone.value(py)));
match err.traceback(py) {
None => assert!(err_clone.traceback(py).is_none()),
Some(tb) => assert!(err_clone.traceback(py).unwrap().is(&tb)),
}
});
Trait Implementations§
Source§impl Error for PyErr
impl Error for PyErr
1.30.0 · Source§fn source(&self) -> Option<&(dyn Error + 'static)>
fn source(&self) -> Option<&(dyn Error + 'static)>
1.0.0 · Source§fn description(&self) -> &str
fn description(&self) -> &str
Source§impl From<AddrParseError> for PyErr
impl From<AddrParseError> for PyErr
Source§fn from(err: AddrParseError) -> PyErr
fn from(err: AddrParseError) -> PyErr
Source§impl From<DecodeUtf16Error> for PyErr
impl From<DecodeUtf16Error> for PyErr
Source§fn from(err: DecodeUtf16Error) -> PyErr
fn from(err: DecodeUtf16Error) -> PyErr
Source§impl From<DowncastError<'_, '_>> for PyErr
impl From<DowncastError<'_, '_>> for PyErr
Convert DowncastError
to Python TypeError
.
Source§fn from(err: DowncastError<'_, '_>) -> PyErr
fn from(err: DowncastError<'_, '_>) -> PyErr
Source§impl From<DowncastIntoError<'_>> for PyErr
impl From<DowncastIntoError<'_>> for PyErr
Convert DowncastIntoError
to Python TypeError
.
Source§fn from(err: DowncastIntoError<'_>) -> PyErr
fn from(err: DowncastIntoError<'_>) -> PyErr
Source§impl From<Error> for PyErr
impl From<Error> for PyErr
Create PyErr
from io::Error
(OSError
except if the io::Error
is wrapping a Python exception,
in this case the exception is returned)
Source§impl From<FromUtf16Error> for PyErr
impl From<FromUtf16Error> for PyErr
Source§fn from(err: FromUtf16Error) -> PyErr
fn from(err: FromUtf16Error) -> PyErr
Source§impl From<FromUtf8Error> for PyErr
impl From<FromUtf8Error> for PyErr
Source§fn from(err: FromUtf8Error) -> PyErr
fn from(err: FromUtf8Error) -> PyErr
Source§impl From<Infallible> for PyErr
impl From<Infallible> for PyErr
Source§fn from(_: Infallible) -> PyErr
fn from(_: Infallible) -> PyErr
Source§impl<W> From<IntoInnerError<W>> for PyErr
impl<W> From<IntoInnerError<W>> for PyErr
Source§fn from(err: IntoInnerError<W>) -> PyErr
fn from(err: IntoInnerError<W>) -> PyErr
Source§impl From<IntoStringError> for PyErr
impl From<IntoStringError> for PyErr
Source§fn from(err: IntoStringError) -> PyErr
fn from(err: IntoStringError) -> PyErr
Source§impl From<ParseBoolError> for PyErr
impl From<ParseBoolError> for PyErr
Source§fn from(err: ParseBoolError) -> PyErr
fn from(err: ParseBoolError) -> PyErr
Source§impl From<ParseFloatError> for PyErr
impl From<ParseFloatError> for PyErr
Source§fn from(err: ParseFloatError) -> PyErr
fn from(err: ParseFloatError) -> PyErr
Source§impl From<ParseIntError> for PyErr
impl From<ParseIntError> for PyErr
Source§fn from(err: ParseIntError) -> PyErr
fn from(err: ParseIntError) -> PyErr
Source§impl From<PyBorrowError> for PyErr
impl From<PyBorrowError> for PyErr
Source§fn from(other: PyBorrowError) -> Self
fn from(other: PyBorrowError) -> Self
Source§impl From<PyBorrowMutError> for PyErr
impl From<PyBorrowMutError> for PyErr
Source§fn from(other: PyBorrowMutError) -> Self
fn from(other: PyBorrowMutError) -> Self
Source§impl From<Report> for PyErr
impl From<Report> for PyErr
Converts eyre::Report
to a PyErr
containing a PyRuntimeError
.
If you want to raise a different Python exception you will have to do so manually. See
PyErr::new
for more information about that.
Source§impl From<TryFromIntError> for PyErr
impl From<TryFromIntError> for PyErr
Source§fn from(err: TryFromIntError) -> PyErr
fn from(err: TryFromIntError) -> PyErr
Source§impl From<TryFromSliceError> for PyErr
impl From<TryFromSliceError> for PyErr
Source§fn from(err: TryFromSliceError) -> PyErr
fn from(err: TryFromSliceError) -> PyErr
Source§impl<'py> IntoPyObject<'py> for &PyErr
impl<'py> IntoPyObject<'py> for &PyErr
Source§type Target = PyBaseException
type Target = PyBaseException
Source§type Output = Bound<'py, <&PyErr as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <&PyErr as IntoPyObject<'py>>::Target>
Source§type Error = Infallible
type Error = Infallible
Source§fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
Source§fn type_output() -> TypeInfo
fn type_output() -> TypeInfo
Source§impl<'py> IntoPyObject<'py> for PyErr
impl<'py> IntoPyObject<'py> for PyErr
Source§type Target = PyBaseException
type Target = PyBaseException
Source§type Output = Bound<'py, <PyErr as IntoPyObject<'py>>::Target>
type Output = Bound<'py, <PyErr as IntoPyObject<'py>>::Target>
Source§type Error = Infallible
type Error = Infallible
Source§fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error>
Source§fn type_output() -> TypeInfo
fn type_output() -> TypeInfo
Auto Trait Implementations§
impl !Freeze for PyErr
impl !RefUnwindSafe for PyErr
impl Send for PyErr
impl Sync for PyErr
impl Unpin for PyErr
impl !UnwindSafe for PyErr
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self>
fn into_either(self, into_left: bool) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left
is true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
self
into a Left
variant of Either<Self, Self>
if into_left(&self)
returns true
.
Converts self
into a Right
variant of Either<Self, Self>
otherwise. Read more