|
1 | 1 | use crate::instance::Bound; |
| 2 | +#[cfg(Py_3_11)] |
| 3 | +use crate::intern; |
2 | 4 | use crate::panic::PanicException; |
3 | 5 | use crate::type_object::PyTypeInfo; |
4 | 6 | use crate::types::any::PyAnyMethods; |
| 7 | +#[cfg(Py_3_11)] |
| 8 | +use crate::types::PyString; |
5 | 9 | use crate::types::{ |
6 | 10 | string::PyStringMethods, traceback::PyTracebackMethods, typeobject::PyTypeMethods, PyTraceback, |
7 | 11 | PyTuple, PyTupleMethods, PyType, |
@@ -655,6 +659,17 @@ impl PyErr { |
655 | 659 | } |
656 | 660 | } |
657 | 661 |
|
| 662 | + /// Equivalent to calling `add_note` on the exception in Python. |
| 663 | + #[cfg(Py_3_11)] |
| 664 | + pub fn add_note<N: for<'py> IntoPyObject<'py, Target = PyString>>( |
| 665 | + &self, |
| 666 | + py: Python<'_>, |
| 667 | + n: N, |
| 668 | + ) -> PyResult<()> { |
| 669 | + self.value(py).call_method1(intern!(py, "add_note"), (n,))?; |
| 670 | + Ok(()) |
| 671 | + } |
| 672 | + |
658 | 673 | #[inline] |
659 | 674 | fn from_state(state: PyErrState) -> PyErr { |
660 | 675 | PyErr { state } |
@@ -1152,4 +1167,21 @@ mod tests { |
1152 | 1167 | warnings.call_method0("resetwarnings").unwrap(); |
1153 | 1168 | }); |
1154 | 1169 | } |
| 1170 | + |
| 1171 | + #[test] |
| 1172 | + #[cfg(Py_3_11)] |
| 1173 | + fn test_add_note() { |
| 1174 | + use crate::types::any::PyAnyMethods; |
| 1175 | + Python::attach(|py| { |
| 1176 | + let err = PyErr::new::<exceptions::PyValueError, _>("original error"); |
| 1177 | + err.add_note(py, "additional context").unwrap(); |
| 1178 | + |
| 1179 | + let notes = err.value(py).getattr("__notes__").unwrap(); |
| 1180 | + assert_eq!(notes.len().unwrap(), 1); |
| 1181 | + assert_eq!( |
| 1182 | + notes.get_item(0).unwrap().extract::<String>().unwrap(), |
| 1183 | + "additional context" |
| 1184 | + ); |
| 1185 | + }); |
| 1186 | + } |
1155 | 1187 | } |
0 commit comments