1 /* Copyright 2019 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 #ifndef TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_PROTO_H_
17 #define TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_PROTO_H_
18
19 #include "absl/strings/str_cat.h"
20 #include "pybind11/pybind11.h"
21
22 namespace tensorflow {
23
CheckProtoType(const pybind11::handle & py_object,const std::string expected_proto_type)24 inline void CheckProtoType(const pybind11::handle& py_object,
25 const std::string expected_proto_type) {
26 // Check the name of the proto object.
27 if (pybind11::hasattr(py_object, "DESCRIPTOR")) {
28 pybind11::handle descriptor = pybind11::getattr(py_object, "DESCRIPTOR");
29 std::string py_object_type =
30 pybind11::cast<std::string>(pybind11::getattr(descriptor, "full_name"));
31
32 if (py_object_type == expected_proto_type) {
33 return;
34 }
35 throw pybind11::type_error(absl::StrCat("Expected an ", expected_proto_type,
36 " proto, but got ",
37 py_object_type));
38 }
39 throw pybind11::type_error(absl::StrCat(
40 std::string(py_object.get_type().str()), " is not a valid proto."));
41 }
42
43 } // namespace tensorflow
44
45 #endif // TENSORFLOW_PYTHON_LIB_CORE_PYBIND11_PROTO_H_
46