Pyo3: Add exceptions to modules

Created on 14 Jan 2020  路  7Comments  路  Source: PyO3/pyo3

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>()?;
}
enhancement needs-design

Most helpful comment

Oh! I really like that!

All 7 comments

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.)

Was this page helpful?
0 / 5 - 0 ratings

Related issues

davidhewitt picture davidhewitt  路  5Comments

mvaled picture mvaled  路  3Comments

rth picture rth  路  5Comments

konstin picture konstin  路  5Comments

nbigaouette picture nbigaouette  路  4Comments