Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Help: Convert rust error enums to python errors #1757

Closed
Shadow53 opened this issue Aug 5, 2021 · 2 comments
Closed

Help: Convert rust error enums to python errors #1757

Shadow53 opened this issue Aug 5, 2021 · 2 comments

Comments

@Shadow53
Copy link

Shadow53 commented Aug 5, 2021

I've been through the docs and guide a few times and I'm stuck figuring out how to go about this.

I have a library that should be usable in both Rust and Python, where Python support is feature-gated. The Rust library defines a bunch of error types as enums using thiserror, e.g.

#[derive(Debug, Error)]
pub enum SomeError {
    #[error("display impl: {0}")]
    VariantOne(#[source] AnotherError),
    #[error(...)]
    VariantTwo(usize),
    #[error(...)]
    VariantThree(#[source] AnotherError),
    #[error(...)]
    VariantFour(#[from] YetAnotherError),
}

What I'm struggling to wrap my head around is the best way to transform this error type into a Python exception.

  1. pyclass fails because it is an enum and not a struct.
  2. create_exception! creates a new type and does not modify an existing one.
  3. impl_exception_boilerplate! seems closest, but conflicts with the implementation of std::error::Error from thiserror. If I modify the code to remove the use of thiserror (i.e. impl things myself), I get a new error that SomeError does not impl PyTypeInfo, which I am not comfortable trying to implement on my own.

Is there something I'm missing, or is this something that just isn't every doable in the current state of PyO3?

@davidhewitt
Copy link
Member

If you want to use builtin Python exception types and be able to return Result<_, SomeError> from #[pymethods], impl From<SomeError> for PyErr might suit what you need?

If you want a custom exception type I would probably recommend #[pyclass(extends=PyException)] to make a separate error classe which the From impl would target.

@Shadow53
Copy link
Author

Shadow53 commented Aug 6, 2021

I'm going with the second option for now.

After further searching, it looks like this is a (partial?) duplicate of #417, so I'll close this in favor of that.

@Shadow53 Shadow53 closed this as completed Aug 6, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants