Python Exceptions
Defining a new exception
You can use the create_exception!
macro to define a new exception type:
module
is the name of the containing module.MyError
is the name of the new exception type.
For example:
use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::types::IntoPyDict;
use pyo3::exceptions::PyException;
create_exception!(mymodule, CustomError, PyException);
fn main() {
let gil = Python::acquire_gil();
let py = gil.python();
let ctx = [("CustomError", py.get_type::<CustomError>())].into_py_dict(py);
py.run("assert str(CustomError) == \"<class 'mymodule.CustomError'>\"", None, Some(&ctx)).unwrap();
py.run("assert CustomError('oops').args == ('oops',)", None, Some(&ctx)).unwrap();
}
When using PyO3 to create an extension module, you can add the new exception to the module like this, so that it is importable from Python:
create_exception!(mymodule, CustomError, PyException);
#[pymodule]
fn mymodule(py: Python, m: &PyModule) -> PyResult<()> {
// ... other elements added to module ...
m.add("CustomError", py.get_type::<CustomError>())?;
Ok(())
}
Raising an exception
To raise an exception, first you need to obtain an exception type and construct a new PyErr
, then call the PyErr::restore
method to write the exception back to the Python interpreter's global state.
use pyo3::{Python, PyErr};
use pyo3::exceptions::PyTypeError;
fn main() {
let gil = Python::acquire_gil();
let py = gil.python();
PyTypeError::new_err("Error").restore(py);
assert!(PyErr::occurred(py));
drop(PyErr::fetch(py));
}
From pyfunction
s and pyclass
methods, returning an Err(PyErr)
is enough;
PyO3 will handle restoring the exception on the Python interpreter side.
If you already have a Python exception instance, you can simply call PyErr::from_instance
.
PyErr::from_instance(py, err).restore(py);
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.
Checking exception types
Python has an isinstance
method to check an object's type,
in PyO3 there is a Python::is_instance
method which does the same thing.
use pyo3::Python;
use pyo3::types::{PyBool, PyList};
fn main() {
let gil = Python::acquire_gil();
let py = gil.python();
assert!(py.is_instance::<PyBool, _>(PyBool::new(py, true)).unwrap());
let list = PyList::new(py, &[1, 2, 3, 4]);
assert!(!py.is_instance::<PyBool, _>(list.as_ref()).unwrap());
assert!(py.is_instance::<PyList, _>(list.as_ref()).unwrap());
}
Python::is_instance
calls the underlying PyType::is_instance
method to do the actual work.
To check the type of an exception, you can similarly do:
Handling Rust errors
The vast majority of operations in this library will return
PyResult<T>
,
which is an alias for the type Result<T, PyErr>
.
A PyErr
represents a Python exception. Errors within the PyO3 library are also exposed as
Python exceptions.
If your code has a custom error type e.g. MyError
, adding an implementation of
std::convert::From<MyError> for PyErr
is usually enough. PyO3 will then automatically convert
your error to a Python exception when needed.
The code snippet above will raise an OSError
in Python if bind()
returns a CustomIOError
.
The std::convert::From<T>
trait is implemented for most of the Rust standard library's error
types so the ?
operator can be used.
The code snippet above will raise a ValueError
in Python if String::parse()
returns an error.
If lazy construction of the Python exception instance is desired, the
PyErrArguments
trait can be implemented. In that case, actual exception argument creation is delayed
until the PyErr
is needed.
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 Rust type
for that exception.
pyo3::exceptions
defines exceptions for several standard library modules.