Skip to content

How to subclass a custom exception? #4440

Closed Answered by davidhewitt
diliop asked this question in Questions
Discussion options

You must be logged in to vote

The challenge here is that on the Python side the subclass SubCustomError needs to have the Rust data for CustomError populated. You already worked that out for your #[new] function.

For the From implementation, I think you can do similarly:

impl From<LocalSubCustomError> for PyErr {
    fn from(error: LocalSubCustomError) -> Self {
        Python::with_gil(|py| {
            let obj = Bound::new(
                py,
                PyClassInitializer::from(LocalCustomError::default())
                    .add_subclass(error)
            ).unwrap();
            PyErr::from_value_bound(obj.into_any())
        })
    }
}

(disclaimer: I didn't check if this compiles! 😬)

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by diliop
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
2 participants