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
Add anyhow-integration
feature which implements From<anyhow::Error> for PyErr
#1822
Merged
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
948f9b6
Add 'anyhow' feature which provides simple From<anyhow::Error> for Py…
chris-laplante 58c3e89
Document `anyhow` feature in the guide
chris-laplante d5313c5
update changelog to document anyhow feature
chris-laplante defc2dd
WIP adding tests
chris-laplante f12db7f
Merge branch 'main' into anyhow
mejrs 3650516
Finish up anyhow feature
mejrs 5297969
Fix formatting
mejrs 1aa3d3d
Fix tests
mejrs a46f11e
Fix tests
mejrs 99caed7
Apply review suggestions
mejrs File filter
Filter by extension
Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -83,6 +83,10 @@ metadata about a Python interpreter. | |
|
||
These features enable conversions between Python types and types from other Rust crates, enabling easy access to the rest of the Rust ecosystem. | ||
|
||
### `anyhow` | ||
|
||
This feature makes it possible to return [`anyhow::Result<T>`](https://docs.rs/anyhow/1.0.43/anyhow/type.Result.html) from functions and methods exposed to Python. It does so by adding `impl From<anyhow::Error> for PyErr`. Currently, the conversion simply stringifies the `anyhow::Error` and shoves it into a `PyRuntimeError`. As a consequence, there is no way to convert a `PyErr` back to the original `anyhow::Error`. It is mostly intended as a developer convenience. | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Similarly I think it'd be nice for this paragraph and the |
||
|
||
### `eyre` | ||
|
||
Adds a dependency on [eyre](https://docs.rs/eyre). Enables a conversion from [eyre](https://docs.rs/eyre)’s [`Report`](https://docs.rs/eyre/latest/eyre/struct.Report.html) type to [`PyErr`](https://docs.rs/pyo3/latest/pyo3/struct.PyErr.html), for easy error handling. | ||
|
@@ -123,3 +127,5 @@ struct User { | |
permissions: Vec<Py<Permission>> | ||
} | ||
``` | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,167 @@ | ||
#![cfg(feature = "anyhow")] | ||
|
||
//! A conversion from [anyhow]’s [`Error`][anyhow_error] type to [`PyErr`]. | ||
//! | ||
//! Use of an error handling library like [anyhow] is common in application code and when you just | ||
//! want error handling to be easy. If you are writing a library or you need more control over your | ||
//! errors you might want to design your own error type instead. | ||
//! | ||
//! This implementation always creates a Python [`RuntimeError`]. You might find that you need to | ||
//! map the error from your Rust code into another Python exception. See [`PyErr::new`] for more | ||
//! information about that. | ||
//! | ||
//! For information about error handling in general, see the [Error handling] chapter of the Rust | ||
//! book. | ||
//! | ||
//! # Setup | ||
//! | ||
//! To use this feature, add this to your **`Cargo.toml`**: | ||
//! | ||
//! ```toml | ||
//! [dependencies] | ||
//! ## change * to the version you want to use, ideally the latest. | ||
//! anyhow = "*" | ||
// workaround for `extended_key_value_attributes`: https://github.com/rust-lang/rust/issues/82768#issuecomment-803935643 | ||
#![cfg_attr(docsrs, cfg_attr(docsrs, doc = concat!("pyo3 = { version = \"", env!("CARGO_PKG_VERSION"), "\", features = [\"anyhow\"] }")))] | ||
#![cfg_attr( | ||
not(docsrs), | ||
doc = "pyo3 = { version = \"*\", features = [\"anyhow\"] }" | ||
)] | ||
//! ``` | ||
//! | ||
//! Note that you must use compatible versions of anyhow and PyO3. | ||
//! The required anyhow version may vary based on the version of PyO3. | ||
//! | ||
//! # Example: Propagating a `PyErr` into [`anyhow::Error`] | ||
//! | ||
//! ```rust | ||
//! use pyo3::prelude::*; | ||
//! use pyo3::wrap_pyfunction; | ||
//! use std::path::PathBuf; | ||
//! | ||
//! // A wrapper around a Rust function. | ||
//! // The pyfunction macro performs the conversion to a PyErr | ||
//! #[pyfunction] | ||
//! fn py_open(filename: PathBuf) -> anyhow::Result<Vec<u8>> { | ||
//! let data = std::fs::read(filename)?; | ||
//! Ok(data) | ||
//! } | ||
//! | ||
//! fn main() { | ||
//! let error = Python::with_gil(|py| -> PyResult<Vec<u8>> { | ||
//! let fun = wrap_pyfunction!(py_open, py)?; | ||
//! let text = fun.call1(("foo.txt",))?.extract::<Vec<u8>>()?; | ||
//! Ok(text) | ||
//! }).unwrap_err(); | ||
//! | ||
//! println!("{}", error); | ||
//! } | ||
//! ``` | ||
//! | ||
//! # Example: Using `anyhow` in general | ||
//! | ||
//! Note that you don't need this feature to convert a [`PyErr`] into an [`anyhow::Error`], because | ||
//! it can already convert anything that implements [`Error`](std::error::Error): | ||
//! | ||
//! ```rust | ||
//! use pyo3::prelude::*; | ||
//! use pyo3::types::PyBytes; | ||
//! | ||
//! // An example function that must handle multiple error types. | ||
//! // | ||
//! // To do this you usually need to design your own error type or use | ||
//! // `Box<dyn Error>`. `anyhow` is a convenient alternative for this. | ||
//! pub fn decompress(bytes: &[u8]) -> anyhow::Result<String> { | ||
//! // An arbitrary example of a Python api you | ||
//! // could call inside an application... | ||
//! // This might return a `PyErr`. | ||
//! let res = Python::with_gil(|py| { | ||
//! let zlib = PyModule::import(py, "zlib")?; | ||
//! let decompress = zlib.getattr("decompress")?; | ||
//! let bytes = PyBytes::new(py, bytes); | ||
//! let value = decompress.call1((bytes,))?; | ||
//! value.extract::<Vec<u8>>() | ||
//! })?; | ||
//! | ||
//! // This might be a `FromUtf8Error`. | ||
//! let text = String::from_utf8(res)?; | ||
//! | ||
//! Ok(text) | ||
//! } | ||
//! | ||
//! fn main() -> anyhow::Result<()> { | ||
//! let bytes: &[u8] = b"x\x9c\x8b\xcc/U(\xce\xc8/\xcdIQ((\xcaOJL\xca\xa9T\ | ||
//! (-NU(\xc9HU\xc8\xc9LJ\xcbI,IUH.\x02\x91\x99y\xc5%\ | ||
//! \xa9\x89)z\x00\xf2\x15\x12\xfe"; | ||
//! let text = decompress(bytes)?; | ||
//! | ||
//! println!("The text is \"{}\"", text); | ||
//! # assert_eq!(text, "You should probably use the libflate crate instead."); | ||
//! Ok(()) | ||
//! } | ||
//! ``` | ||
//! | ||
//! [anyhow]: https://docs.rs/anyhow/ "A trait object based error system for easy idiomatic error handling in Rust applications." | ||
//! [anyhow_error]: https://docs.rs/anyhow/latest/anyhow/struct.Error.html "Anyhows `Error` type, a wrapper around a dynamic error type" | ||
//! [`RuntimeError`]: https://docs.python.org/3/library/exceptions.html#RuntimeError "Built-in Exceptions — Python documentation" | ||
//! [Error handling]: https://doc.rust-lang.org/book/ch09-02-recoverable-errors-with-result.html "Recoverable Errors with Result - The Rust Programming Language" | ||
|
||
use crate::exceptions::PyRuntimeError; | ||
use crate::PyErr; | ||
|
||
impl From<anyhow::Error> for PyErr { | ||
fn from(err: anyhow::Error) -> Self { | ||
PyRuntimeError::new_err(format!("{:?}", err)) | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod test_anyhow { | ||
use pyo3::prelude::*; | ||
use pyo3::types::IntoPyDict; | ||
|
||
use anyhow::{anyhow, bail, Context, Result}; | ||
|
||
fn f() -> Result<()> { | ||
use std::io; | ||
bail!(io::Error::new(io::ErrorKind::PermissionDenied, "oh no!")); | ||
} | ||
|
||
fn g() -> Result<()> { | ||
f().context("f failed") | ||
} | ||
|
||
fn h() -> Result<()> { | ||
g().context("g failed") | ||
} | ||
|
||
#[test] | ||
fn test_pyo3_exception_contents() { | ||
let err = h().unwrap_err(); | ||
let expected_contents = format!("{:?}", err); | ||
let pyerr = PyErr::from(err); | ||
|
||
Python::with_gil(|py| { | ||
let locals = [("err", pyerr)].into_py_dict(py); | ||
let pyerr = py.run("raise err", None, Some(locals)).unwrap_err(); | ||
assert_eq!(pyerr.pvalue(py).to_string(), expected_contents); | ||
}) | ||
} | ||
|
||
fn k() -> Result<()> { | ||
Err(anyhow!("Some sort of error")) | ||
} | ||
|
||
#[test] | ||
fn test_pyo3_exception_contents2() { | ||
let err = k().unwrap_err(); | ||
let expected_contents = format!("{:?}", err); | ||
let pyerr = PyErr::from(err); | ||
|
||
Python::with_gil(|py| { | ||
let locals = [("err", pyerr)].into_py_dict(py); | ||
let pyerr = py.run("raise err", None, Some(locals)).unwrap_err(); | ||
assert_eq!(pyerr.pvalue(py).to_string(), expected_contents); | ||
}) | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Let's put this in the
Packaging
section too and make sure this and theeyre
entry are written the same way?