pyo3 icon indicating copy to clipboard operation
pyo3 copied to clipboard

Add exceptions to modules

Open fubuloubu opened this issue 5 years ago • 9 comments

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

fubuloubu avatar Jan 14 '20 14:01 fubuloubu

Possibly one for the new syntax proposed in #694 . (Seems like use MyException could be possible in that syntax.)

davidhewitt avatar Jan 15 '20 08:01 davidhewitt

@davidhewitt you mean something like:

#[pymodule]
mod my_mod {
    #[pyexception]
    enum MyException { ... }

    ...
}

fubuloubu avatar Jan 15 '20 12:01 fubuloubu

Quite possibly, yes. Or also something along the lines of

#[pyexception]
enum MyException {  }

#[pymodule]
mod my_mod {
    use super::MyException;
}

davidhewitt avatar Jan 15 '20 14:01 davidhewitt

Oh! I really like that!

fubuloubu avatar Jan 15 '20 18:01 fubuloubu

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 avatar Jul 30 '20 01:07 hwchen

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

davidhewitt avatar Jul 30 '20 06:07 davidhewitt

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

davidhewitt avatar Sep 01 '20 22:09 davidhewitt

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 avatar Sep 25 '21 14:09 jnicholls

@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 😅

davidhewitt avatar Sep 26 '21 09:09 davidhewitt