pyo3/types/traceback.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186
use crate::err::{error_on_minusone, PyResult};
use crate::types::{any::PyAnyMethods, string::PyStringMethods, PyString};
#[cfg(feature = "gil-refs")]
use crate::PyNativeType;
use crate::{ffi, Bound, PyAny};
/// Represents a Python traceback.
///
/// Values of this type are accessed via PyO3's smart pointers, e.g. as
/// [`Py<PyTraceback>`][crate::Py] or [`Bound<'py, PyTraceback>`][Bound].
///
/// For APIs available on traceback objects, see the [`PyTracebackMethods`] trait which is implemented for
/// [`Bound<'py, PyTraceback>`][Bound].
#[repr(transparent)]
pub struct PyTraceback(PyAny);
pyobject_native_type_core!(
PyTraceback,
pyobject_native_static_type_object!(ffi::PyTraceBack_Type),
#checkfunction=ffi::PyTraceBack_Check
);
#[cfg(feature = "gil-refs")]
impl PyTraceback {
/// Formats the traceback as a string.
///
/// This does not include the exception type and value. The exception type and value can be
/// formatted using the `Display` implementation for `PyErr`.
///
/// # Example
///
/// The following code formats a Python traceback and exception pair from Rust:
///
/// ```rust
/// # use pyo3::{Python, PyResult, prelude::PyTracebackMethods};
/// # let result: PyResult<()> =
/// Python::with_gil(|py| {
/// let err = py
/// .run_bound("raise Exception('banana')", None, None)
/// .expect_err("raise will create a Python error");
///
/// let traceback = err.traceback_bound(py).expect("raised exception will have a traceback");
/// assert_eq!(
/// format!("{}{}", traceback.format()?, err),
/// "\
/// Traceback (most recent call last):
/// File \"<string>\", line 1, in <module>
/// Exception: banana\
/// "
/// );
/// Ok(())
/// })
/// # ;
/// # result.expect("example failed");
/// ```
pub fn format(&self) -> PyResult<String> {
self.as_borrowed().format()
}
}
/// Implementation of functionality for [`PyTraceback`].
///
/// These methods are defined for the `Bound<'py, PyTraceback>` smart pointer, so to use method call
/// syntax these methods are separated into a trait, because stable Rust does not yet support
/// `arbitrary_self_types`.
#[doc(alias = "PyTraceback")]
pub trait PyTracebackMethods<'py>: crate::sealed::Sealed {
/// Formats the traceback as a string.
///
/// This does not include the exception type and value. The exception type and value can be
/// formatted using the `Display` implementation for `PyErr`.
///
/// # Example
///
/// The following code formats a Python traceback and exception pair from Rust:
///
/// ```rust
/// # use pyo3::{Python, PyResult, prelude::PyTracebackMethods};
/// # let result: PyResult<()> =
/// Python::with_gil(|py| {
/// let err = py
/// .run_bound("raise Exception('banana')", None, None)
/// .expect_err("raise will create a Python error");
///
/// let traceback = err.traceback_bound(py).expect("raised exception will have a traceback");
/// assert_eq!(
/// format!("{}{}", traceback.format()?, err),
/// "\
/// Traceback (most recent call last):
/// File \"<string>\", line 1, in <module>
/// Exception: banana\
/// "
/// );
/// Ok(())
/// })
/// # ;
/// # result.expect("example failed");
/// ```
fn format(&self) -> PyResult<String>;
}
impl<'py> PyTracebackMethods<'py> for Bound<'py, PyTraceback> {
fn format(&self) -> PyResult<String> {
let py = self.py();
let string_io = py
.import_bound(intern!(py, "io"))?
.getattr(intern!(py, "StringIO"))?
.call0()?;
let result = unsafe { ffi::PyTraceBack_Print(self.as_ptr(), string_io.as_ptr()) };
error_on_minusone(py, result)?;
let formatted = string_io
.getattr(intern!(py, "getvalue"))?
.call0()?
.downcast::<PyString>()?
.to_cow()?
.into_owned();
Ok(formatted)
}
}
#[cfg(test)]
mod tests {
use crate::{
types::{any::PyAnyMethods, dict::PyDictMethods, traceback::PyTracebackMethods, PyDict},
IntoPy, PyErr, Python,
};
#[test]
fn format_traceback() {
Python::with_gil(|py| {
let err = py
.run_bound("raise Exception('banana')", None, None)
.expect_err("raising should have given us an error");
assert_eq!(
err.traceback_bound(py).unwrap().format().unwrap(),
"Traceback (most recent call last):\n File \"<string>\", line 1, in <module>\n"
);
})
}
#[test]
fn test_err_from_value() {
Python::with_gil(|py| {
let locals = PyDict::new_bound(py);
// Produce an error from python so that it has a traceback
py.run_bound(
r"
try:
raise ValueError('raised exception')
except Exception as e:
err = e
",
None,
Some(&locals),
)
.unwrap();
let err = PyErr::from_value_bound(locals.get_item("err").unwrap().unwrap());
let traceback = err.value_bound(py).getattr("__traceback__").unwrap();
assert!(err.traceback_bound(py).unwrap().is(&traceback));
})
}
#[test]
fn test_err_into_py() {
Python::with_gil(|py| {
let locals = PyDict::new_bound(py);
// Produce an error from python so that it has a traceback
py.run_bound(
r"
def f():
raise ValueError('raised exception')
",
None,
Some(&locals),
)
.unwrap();
let f = locals.get_item("f").unwrap().unwrap();
let err = f.call0().unwrap_err();
let traceback = err.traceback_bound(py).unwrap();
let err_object = err.clone_ref(py).into_py(py).into_bound(py);
assert!(err_object.getattr("__traceback__").unwrap().is(&traceback));
})
}
}