% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/python.R
\name{py_clear_last_error}
\alias{py_clear_last_error}
\alias{py_last_error}
\title{Get or (re)set the last Python error encountered.}
\usage{
py_clear_last_error()

py_last_error(exception)
}
\arguments{
\item{exception}{A python exception object. If provided, the provided
exception is set as the last exception.}
}
\value{
For \code{py_last_error()}, \code{NULL} if no error has yet been encountered.
Otherwise, a named list with entries:
\itemize{
\item \code{"type"}: R string, name of the exception class.
\item \code{"value"}: R string, formatted exception message.
\item \code{"traceback"}: R character vector, the formatted python traceback,
\item \code{"message"}: The full formatted raised exception, as it would be printed in
Python. Includes the traceback, type, and value.
\item \code{"r_trace"}: A \code{data.frame} with class \code{rlang_trace} and columns:
\itemize{
\item \code{call}: The R callstack, \code{full_call}, summarized for pretty printing.
\item \code{full_call}: The R callstack. (Output of \code{sys.calls()} at the error callsite).
\item \code{parent}: The parent of each frame in callstack. (Output of \code{sys.parents()} at the error callsite).
\item Additional columns for internals use: \code{namespace}, \code{visible}, \code{scope}.
}
}

And attribute \code{"exception"}, a \code{'python.builtin.Exception'} object.

The named list has \code{class} \code{"py_error"}, and has a default \code{print} method
that is the equivalent of \code{cat(py_last_error()$message)}.
}
\description{
Get or (re)set the last Python error encountered.
}
\examples{
\dontrun{

# see last python exception with R traceback
reticulate::py_last_error()

# see the full R callstack from the last Python exception
reticulate::py_last_error()$r_trace$full_call

# run python code that might error,
# without modifying the user-visible python exception

safe_len <- function(x) {
  last_err <- py_last_error()
  tryCatch({
    # this might raise a python exception if x has no `__len__` method.
    import_builtins()$len(x)
  }, error = function(e) {
    # py_last_error() was overwritten, is now "no len method for 'object'"
    py_last_error(last_err) # restore previous exception
    -1L
  })
}

safe_len(py_eval("object"))
}

}
