From the course: Using Rust with Python

Unlock this course with a free trial

Join today to access over 23,200 courses taught by industry experts.

PyO3 exceptions

PyO3 exceptions

- [Instructor] Python exception handling in Rust is an interesting problem to deal with because of the fact that you are able to get a different type of response in Rust, right, where you have errors, but in Python you have exceptions. So how do you do this? Well, first up, in raising exceptions here, you can see here that you can use a new PyErr instance or PyErr from type to create a Python exception, and then PyErr raise to then raise it in Python. On the other hand, to handle the exceptions, you can use .MapError to move a Rust result error into a Python exception, or use Py function attribute and return Py result. And you can see this in this function from Rust below. So let's go ahead and take a look at how this works in action here with some real code. I have a project here called rust-exceptions, and inside of this rust-exceptions here I have some Python code. But first, let's look at the lib here. So we are using PyO3, and I'm using PyO3 exceptions here, and I have a…

Contents