pyo3: Add a proc macro for exceptions

I would be great to have a custom derive for exceptions, similar but more powerful than create_exception. This would e.g. allow reimplementing JSONDecodeError:

#[pyexception(module = json)]
struct JSONDecodeError {
    msg: String,
    doc: String,
    pos: usize,
    lineno: Option<usize>,
    colno: Option<usize>,
}

The steps required are roughly:

  1. Look at examples in syn and pyo3’s existing proc macros to learn how to implement a proc macro. wasm-bindgen could be another useful resource.
  2. Implement the macro using the existing impl_exception_boilerplate and create_exception_type_object macros. The #[proc_macro_attribute] function should go in pyo3cls/src/lib.rs, while the actual implementation should be in pyo3-derive-backend.
  3. Write tests. Most important is one for a struct without members and one with at least 2 members.
  4. Add a usage example to the guide. You can just copy one of the tests for that.

If you want to work on implementing this or have any questions, feel free ask here or on gitter!

About this issue

  • Original URL
  • State: open
  • Created 8 years ago
  • Reactions: 8
  • Comments: 22 (14 by maintainers)

Most upvoted comments

I’m nominating this for 0.12 - I actually already have a PR almost ready for #682 which would lay the groundwork for this.

Slightly modified it to also accept a message + code:

fn raise_MemoryError(message: String, e: MemError) -> PyErr {
    Python::with_gil(|py| {
        let icicle = py.import("icicle").unwrap();
        let exception = icicle.getattr("MemoryError").unwrap();
        let xx = MemoryErrorCode::from(e);
        let args = (message, xx, );
        let inst = exception.call1(args).unwrap();
        PyErr::from_value(inst)
    })
}

#[pymodule]
fn icicle(py: Python<'_>, m: &PyModule) -> PyResult<()> {
    PyModule::from_code(py, r#"
class MemoryError(Exception):
    def __init__(self, message, code):
        super().__init__(message)
        self.code = code
    def __str__(self):
        return f"{super().__str__()}: {self.code}"
"#, "icicle_exceptions.py", "icicle")?;
    Ok(())
}

Super ugly, but this ended up working exactly as I needed:

    try:
        vm.mem_protect(addr, 0x2000, icicle.MemoryProtection.ExecuteRead)
    except icicle.MemoryError as x:
        message = x.args[0]
        print(message, x.code)

I’d like to try my hand at this. Would that be fine?

If so, I’m not super familiar with the details here, so would this issue be a good place to ask questions?

I managed to get the basics of this working by loading a python string:

fn raise_MemoryError() -> PyErr {
    Python::with_gil(|py| {
        let icicle = py.import("icicle").unwrap();
        let exception = icicle.getattr("MemoryError").unwrap();
        let inst = exception.call0().unwrap();
        PyErr::from_value(inst)
    })
}

#[pymodule]
fn icicle(py: Python<'_>, m: &PyModule) -> PyResult<()> {
    PyModule::from_code(py, r#"
class MemoryError(Exception):
    pass
"#, "icicle_exceptions.py", "icicle")?;
    Ok(())
}

Obviously this is extremely ugly, but I couldn’t figure out how to do this the ‘proper’ way…

(Meta point: I’m pretty sure this ticket should have the “Good First Issue” label dropped. It’s been open for a few years and it doesn’t seem to have a trivial solution)