• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2018 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 <Python.h>
17 
18 #include "tensorflow/python/lib/core/py_exception_registry.h"
19 
20 namespace tensorflow {
21 
22 PyExceptionRegistry* PyExceptionRegistry::singleton_ = nullptr;
23 
Init(PyObject * code_to_exc_type_map)24 void PyExceptionRegistry::Init(PyObject* code_to_exc_type_map) {
25   DCHECK(singleton_ == nullptr) << "PyExceptionRegistry::Init() already called";
26   singleton_ = new PyExceptionRegistry;
27 
28   DCHECK(PyDict_Check(code_to_exc_type_map));
29   PyObject* key;
30   PyObject* value;
31   Py_ssize_t pos = 0;
32   while (PyDict_Next(code_to_exc_type_map, &pos, &key, &value)) {
33     TF_Code code = static_cast<TF_Code>(PyLong_AsLong(key));
34     singleton_->exc_types_[code] = value;
35     // The exception classes should also have the lifetime of the process, but
36     // incref just in case.
37     Py_INCREF(value);
38   }
39 }
40 
Lookup(TF_Code code)41 PyObject* PyExceptionRegistry::Lookup(TF_Code code) {
42   DCHECK(singleton_ != nullptr) << "Must call PyExceptionRegistry::Init() "
43                                    "before PyExceptionRegistry::Lookup()";
44   DCHECK_NE(code, TF_OK);
45   DCHECK(singleton_->exc_types_.find(code) != singleton_->exc_types_.end())
46       << "Unknown error code passed to PyExceptionRegistry::Lookup: " << code;
47   return singleton_->exc_types_[code];
48 }
49 
50 }  // namespace tensorflow
51