Extracting and matching Python Error in Rust #3759
-
[I'm relatively new to Rust, keep that in mind] I want to extract the Python Error class (KeyError, TypeError,...) from PyErr. This is what I'm using at the moment e.to_string().split_once(":").unwrap().0 It works, but feels a little hacky and wanted to see if there's a better approach. When I debug the entire PyErr, I can see that it already has a field for it
I'm aware of the |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
You definitely need a GIL token, but it should be easy to come by. Either you need to wrap your call to fn is_key_error(err: &PyErr) -> bool {
Python::with_gil(|py| {
err.is_instance_of::<PyKeyError>(py)
})
} or better yet, you just add |
Beta Was this translation helpful? Give feedback.
You definitely need a GIL token, but it should be easy to come by. Either you need to wrap your call to
is_instance_of
usingwith_gil
, e.g.or better yet, you just add
py: Python
as an argument to your#[pyfunction]
or#[pymethod]
and PyO3 will provide you with a token. (The GIL is already held when PyO3 calls your function or method, hence we can just pass on the token if you request it.)