Home | History | Annotate | Download | only in core
      1 /* Copyright 2015 The TensorFlow Authors. All Rights Reserved.
      2 
      3 Licensed under the Apache License, Version 2.0 (the "License");
      4 you may not use this file except in compliance with the License.
      5 You may obtain a copy of the License at
      6 
      7     http://www.apache.org/licenses/LICENSE-2.0
      8 
      9 Unless required by applicable law or agreed to in writing, software
     10 distributed under the License is distributed on an "AS IS" BASIS,
     11 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     12 See the License for the specific language governing permissions and
     13 limitations under the License.
     14 ==============================================================================*/
     15 
     16 #include "tensorflow/python/lib/core/py_util.h"
     17 
     18 #include "tensorflow/core/lib/core/errors.h"
     19 #include "tensorflow/core/lib/strings/strcat.h"
     20 #include <Python.h>
     21 
     22 namespace tensorflow {
     23 namespace {
     24 
     25 // py.__class__.__name__
     26 const char* ClassName(PyObject* py) {
     27 /* PyPy doesn't have a separate C API for old-style classes. */
     28 #if PY_MAJOR_VERSION < 3 && !defined(PYPY_VERSION)
     29   if (PyClass_Check(py))
     30     return PyString_AS_STRING(
     31         CHECK_NOTNULL(reinterpret_cast<PyClassObject*>(py)->cl_name));
     32   if (PyInstance_Check(py))
     33     return PyString_AS_STRING(CHECK_NOTNULL(
     34         reinterpret_cast<PyInstanceObject*>(py)->in_class->cl_name));
     35 #endif
     36   if (Py_TYPE(py) == &PyType_Type) {
     37     return reinterpret_cast<PyTypeObject*>(py)->tp_name;
     38   }
     39   return Py_TYPE(py)->tp_name;
     40 }
     41 
     42 }  // end namespace
     43 
     44 string PyExceptionFetch() {
     45   CHECK(PyErr_Occurred())
     46       << "Must only call PyExceptionFetch after an exception.";
     47   PyObject* ptype;
     48   PyObject* pvalue;
     49   PyObject* ptraceback;
     50   PyErr_Fetch(&ptype, &pvalue, &ptraceback);
     51   PyErr_NormalizeException(&ptype, &pvalue, &ptraceback);
     52   string err = ClassName(ptype);
     53   if (pvalue) {
     54     PyObject* str = PyObject_Str(pvalue);
     55     if (str) {
     56 #if PY_MAJOR_VERSION < 3
     57       strings::StrAppend(&err, ": ", PyString_AS_STRING(str));
     58 #else
     59       strings::StrAppend(&err, ": ", PyUnicode_AsUTF8(str));
     60 #endif
     61       Py_DECREF(str);
     62     }
     63     Py_DECREF(pvalue);
     64   }
     65   Py_DECREF(ptype);
     66   Py_XDECREF(ptraceback);
     67   return err;
     68 }
     69 
     70 }  // end namespace tensorflow
     71