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:
- 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.
- Implement the macro using the existing impl_exception_boilerplate and create_exception_type_object macros. The
#[proc_macro_attribute]function should go inpyo3cls/src/lib.rs, while the actual implementation should be inpyo3-derive-backend. - Write tests. Most important is one for a struct without members and one with at least 2 members.
- 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)
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:
Super ugly, but this ended up working exactly as I needed:
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:
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)