Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions guide/src/function/error-handling.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,9 @@ fn wrapped_get_x() -> Result<i32, MyOtherError> {
# }
```

## Notes

In Python 3.11 and up, notes can be added to Python exceptions to provide additional debugging information when printing the exception. In PyO3, you can use the `add_note` method on `PyErr` to accomplish this functionality.

[`From`]: https://doc.rust-lang.org/stable/std/convert/trait.From.html
[`Result<T, E>`]: https://doc.rust-lang.org/stable/std/result/enum.Result.html
Expand Down
1 change: 1 addition & 0 deletions newsfragments/5489.added.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Added `PyErr::add_note`
33 changes: 33 additions & 0 deletions src/err/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
use crate::instance::Bound;
#[cfg(Py_3_11)]
use crate::intern;
use crate::panic::PanicException;
use crate::type_object::PyTypeInfo;
use crate::types::any::PyAnyMethods;
#[cfg(Py_3_11)]
use crate::types::PyString;
use crate::types::{
string::PyStringMethods, traceback::PyTracebackMethods, typeobject::PyTypeMethods, PyTraceback,
PyTuple, PyTupleMethods, PyType,
Expand Down Expand Up @@ -655,6 +659,18 @@ impl PyErr {
}
}

/// Equivalent to calling `add_note` on the exception in Python.
#[cfg(Py_3_11)]
pub fn add_note<N: for<'py> IntoPyObject<'py, Target = PyString>>(
&self,
py: Python<'_>,
note: N,
) -> PyResult<()> {
self.value(py)
.call_method1(intern!(py, "add_note"), (note,))?;
Ok(())
}

#[inline]
fn from_state(state: PyErrState) -> PyErr {
PyErr { state }
Expand Down Expand Up @@ -1152,4 +1168,21 @@ mod tests {
warnings.call_method0("resetwarnings").unwrap();
});
}

#[test]
#[cfg(Py_3_11)]
fn test_add_note() {
use crate::types::any::PyAnyMethods;
Python::attach(|py| {
let err = PyErr::new::<exceptions::PyValueError, _>("original error");
err.add_note(py, "additional context").unwrap();

let notes = err.value(py).getattr("__notes__").unwrap();
assert_eq!(notes.len().unwrap(), 1);
assert_eq!(
notes.get_item(0).unwrap().extract::<String>().unwrap(),
"additional context"
);
});
}
}
Loading