• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright 2021 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_COMPILER_XLA_PYTHON_PYBIND11_UTILS_H_
17 #define TENSORFLOW_COMPILER_XLA_PYTHON_PYBIND11_UTILS_H_
18 
19 #include <Python.h>
20 
21 #include <optional>
22 #include <string>
23 
24 #include "pybind11/pybind11.h"
25 #include "pybind11/pytypes.h"
26 #include "tensorflow/compiler/xla/status_macros.h"
27 #include "tensorflow/compiler/xla/util.h"
28 
29 namespace jax {
30 
31 // This file contains utilities to write Python wrapers using the C API.
32 // It's used for performance critical code such as PyBuffer, jax.jit or
33 // jax.pmap.
34 
35 // Helpers for building Python properties
36 template <typename Func>
property_readonly(Func && get)37 pybind11::object property_readonly(Func&& get) {
38   pybind11::handle property(reinterpret_cast<PyObject*>(&PyProperty_Type));
39   return property(pybind11::cpp_function(std::forward<Func>(get)),
40                   pybind11::none(), pybind11::none(), "");
41 }
42 
43 template <typename GetFunc, typename SetFunc>
property(GetFunc && get,SetFunc && set)44 pybind11::object property(GetFunc&& get, SetFunc&& set) {
45   pybind11::handle property(reinterpret_cast<PyObject*>(&PyProperty_Type));
46   return property(pybind11::cpp_function(std::forward<GetFunc>(get)),
47                   pybind11::cpp_function(std::forward<SetFunc>(set)),
48                   pybind11::none(), "");
49 }
50 
51 template <typename Constructor>
def_static(Constructor && constructor)52 pybind11::object def_static(Constructor&& constructor) {
53   pybind11::handle property(reinterpret_cast<PyObject*>(&PyProperty_Type));
54   return pybind11::staticmethod(
55       pybind11::cpp_function(std::forward<Constructor>(constructor)));
56 }
57 
58 }  // namespace jax
59 
60 #endif  // TENSORFLOW_COMPILER_XLA_PYTHON_PYBIND11_UTILS_H_
61