pyo3
pyo3 copied to clipboard
Add exceptions to modules
After creating a new exception using:
create_exception!(my_module, MyException, ExceptionClass);
It is natural that I would want to make it available as an import within my python module:
from my_module import MyException
However, in order to do this, I had to do some deep Kung Foo action:
#[pymodule]
fn my_module(py: Python, m: PyModule) {
m.add("MyException", py.get_type::<MyException>())?;
}
It would be nice to have an easier API for this:
#[pymodule]
fn my_module(_py: Python, m: PyModule) {
m.add_exception::<MyException>()?;
}
Possibly one for the new syntax proposed in #694 . (Seems like use MyException could be possible in that syntax.)
@davidhewitt you mean something like:
#[pymodule]
mod my_mod {
#[pyexception]
enum MyException { ... }
...
}
Quite possibly, yes. Or also something along the lines of
#[pyexception]
enum MyException { }
#[pymodule]
mod my_mod {
use super::MyException;
}
Oh! I really like that!
Just wanted to mention that I needed this exact use case, and it would have been more straightforward for me if m.add() was documented right in the Exceptions page. If you also feel it would be an improvement, I can make a PR.
@hwchen thanks for the offer but I'm about to rework create_exception to allow adding custom fields (similar to #[pyclass]) , so I think your effort might be overwritten almost immediately. I agree we should improve this for 0.12 though.
(In the end @birkenfeld did end up submitting this exact PR... many thanks! Also, I've suggested we push the #[pyexception] macro back to 0.13, so I'm going to do the same here.)
Noticing this continues to get pushed to further releases. Let us know if help is desired, we can follow the design you have envisioned. And officially, <bump/>
@jnicholls thanks for the interest, help is very welcome.
The design which I prefer at the moment is to make #[pyclass] and PyModule::add_class the correct way to make custom exception classes and add them to modules rather than having a different API.
This is already possible today, but it's not the most user-friendly or well documented. For the remaining work, see https://github.com/PyO3/pyo3/issues/295#issuecomment-852358088
If you're interested in coming along with ideas and implementation, I'd be really happy to see this complete! I've been busy working on other pieces of pyo3 😅