1 /* Copyright 2020 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 #include "tensorflow/python/framework/py_context_manager.h"
16 
17 #include <map>
18 
19 #include "tensorflow/core/platform/logging.h"
20 
21 namespace tensorflow {
22 
Enter(PyObject * py_context_manager)23 bool PyContextManager::Enter(PyObject* py_context_manager) {
24   if (context_manager_) {
25     PyErr_SetString(
26         PyExc_ValueError,
27         "tensorflow::PyContextManager::Enter must be called at most once.");
28   }
29   if (!py_context_manager) return false;
30   context_manager_.reset(py_context_manager);
31   static char _enter[] = "__enter__";
32   var_.reset(PyObject_CallMethod(context_manager_.get(), _enter, nullptr));
33   return var_ != nullptr;
34 }
35 
~PyContextManager()36 PyContextManager::~PyContextManager() {
37   if (var_) {
38     static char _exit[] = "__exit__";
39     static char _ooo[] = "OOO";
40     if (PyErr_Occurred()) {
41       PyObject *type, *value, *traceback;
42       PyErr_Fetch(&type, &value, &traceback);
43       value = value ? value : Py_None;
44       traceback = traceback ? traceback : Py_None;
45       Safe_PyObjectPtr result(PyObject_CallMethod(
46           context_manager_.get(), _exit, _ooo, type, value, traceback));
47       if (result) {
48         if (PyObject_IsTrue(result.get())) {
49           PyErr_SetString(
50               PyExc_ValueError,
51               "tensorflow::PyContextManager::Enter does not support "
52               "context managers that suppress exceptions.");
53         } else {
54           PyErr_Restore(type, value, traceback);
55         }
56       }
57     } else {
58       PyObject* result = PyObject_CallMethod(context_manager_.get(), _exit,
59                                              _ooo, Py_None, Py_None, Py_None);
60       if (result) {
61         Py_DECREF(result);
62       } else {
63         LOG(ERROR)
64             << "A context manager wrapped by tensorflow::PyContextManager "
65                "raised a new exception from its __new__ method.  This behavior "
66                "is not supported by PyContextManager, and the exception is "
67                "being suppressed.";
68         PyErr_Clear();
69       }
70     }
71   }
72 }
73 
74 }  // namespace tensorflow
75