Macro pyo3::create_exception[][src]

macro_rules! create_exception {
    ($module : ident, $name : ident, $base : ty) => { ... };
Expand description

Defines a new exception type.


create_exception!(module, MyError, BaseException)

  • 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::PyException.


use pyo3::prelude::*;
use pyo3::create_exception;
use pyo3::types::IntoPyDict;
use pyo3::exceptions::PyException;

create_exception!(mymodule, CustomError, PyException);

Python::with_gil(|py| {
    let error_type = py.get_type::<CustomError>();
    let ctx = [("CustomError", error_type)].into_py_dict(py);
    let type_description: String = py
        .eval("str(CustomError)", None, Some(&ctx))
    assert_eq!(type_description, "<class 'mymodule.CustomError'>");
    pyo3::py_run!(py, *ctx, "assert CustomError('oops').args == ('oops',)");