Skip to content

Commit f1435c7

Browse files
committed
Extract exception name via tp_name
This is faster than dynamically looking up __name__ via GetAttrString. Note though that the runtime of the code throwing an error_already_set will be dominated by stack unwinding so the improvement will not be noticeable. Before: 396 ns ± 0.913 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) After: 277 ns ± 0.549 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each) Benchmark: const std::string foo() { PyErr_SetString(PyExc_KeyError, ""); const std::string &s = py::detail::error_string(); PyErr_Clear(); return s; } PYBIND11_MODULE(foo, m) { m.def("foo", &::foo); }
1 parent e289e0e commit f1435c7

File tree

1 file changed

+1
-1
lines changed

1 file changed

+1
-1
lines changed

include/pybind11/cast.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -413,7 +413,7 @@ PYBIND11_NOINLINE inline std::string error_string(PyObject* type, PyObject* valu
413413
// normalized by the caller?
414414
std::string errorString;
415415
if (type) {
416-
errorString += handle(type).attr("__name__").cast<std::string>();
416+
errorString += static_cast<const std::string>(reinterpret_cast<PyTypeObject*>(type)->tp_name);
417417
errorString += ": ";
418418
}
419419
if (value)

0 commit comments

Comments
 (0)