3737#include " status_macros.h"
3838#include < pybind11/pybind11.h>
3939#include < pybind11/stl.h>
40- #include " pybind11_abseil/status_casters.h"
4140
4241namespace cel_python {
4342
@@ -56,7 +55,7 @@ static std::shared_ptr<PyCelEnvInternal> GetEnvFromContext(
5655
5756void PyCelFunction::DefinePythonBindings (pybind11::module & m) {
5857 py::class_<PyCelFunction, std::shared_ptr<PyCelFunction>>(m, " Function" )
59- .def (py::init<std::string, std::vector<PyCelType>, bool , PyObject* ,
58+ .def (py::init<std::string, std::vector<PyCelType>, bool , py::object ,
6059 PyCelType>(),
6160 py::arg (" function_name" ), py::arg (" parameters" ),
6261 py::arg (" is_member" ), py::arg (" impl" ),
@@ -65,36 +64,21 @@ void PyCelFunction::DefinePythonBindings(pybind11::module& m) {
6564
6665PyCelFunction::PyCelFunction (std::string function_name,
6766 std::vector<PyCelType> parameters, bool is_member,
68- PyObject* impl, PyCelType return_type)
67+ py::object impl, PyCelType return_type)
6968 : function_name_(std::move(function_name)),
7069 return_type_ (std::move(return_type)),
7170 parameters_(std::move(parameters)),
7271 is_member_(is_member),
73- impl_(impl) {
72+ impl_(std::move( impl) ) {
7473 ABSL_CHECK (PyGILState_Check ());
75- Py_XINCREF (impl_);
7674}
7775
78- PyCelFunction::~PyCelFunction () {
79- auto gil_state = PyGILState_Ensure ();
80- Py_XDECREF (impl_);
81- PyGILState_Release (gil_state);
82- };
83-
8476PyCelFunctionAdapter::PyCelFunctionAdapter (std::string function_name,
8577 PyCelType return_type,
86- PyObject* py_function)
78+ py::object py_function)
8779 : function_name_(std::move(function_name)),
8880 return_type_(std::move(return_type)),
89- py_function_(py_function) {
90- Py_XINCREF (py_function_);
91- }
92-
93- PyCelFunctionAdapter::~PyCelFunctionAdapter () {
94- auto gil_state = PyGILState_Ensure ();
95- Py_XDECREF (py_function_);
96- PyGILState_Release (gil_state);
97- }
81+ py_function_(std::move(py_function)) {}
9882
9983absl::StatusOr<cel::Value> PyCelFunctionAdapter::Invoke (
10084 absl::Span<const cel::Value> args,
@@ -110,7 +94,7 @@ absl::StatusOr<cel::Value> PyCelFunctionAdapter::Invoke(
11094 CelValueToPyObject (args[i], env, py_arena,
11195 /* plain_value=*/ true ));
11296 }
113- PyObject* result = PyObject_CallObject (py_function_, py_args);
97+ PyObject* result = PyObject_CallObject (py_function_. ptr () , py_args);
11498 absl::Status status = PyErr_toStatus ();
11599 if (!status.ok ()) {
116100 return cel::ErrorValue (status);
@@ -119,8 +103,9 @@ absl::StatusOr<cel::Value> PyCelFunctionAdapter::Invoke(
119103 return PyObjectToCelValue (
120104 result, return_type_,
121105 [this ]() {
122- return absl::StrFormat (" Python function '%s'" ,
123- PyUnicode_AsUTF8 (PyObject_Repr (py_function_)));
106+ return absl::StrFormat (
107+ " Python function '%s'" ,
108+ PyUnicode_AsUTF8 (PyObject_Repr (py_function_.ptr ())));
124109 },
125110 env, context.arena ());
126111};
0 commit comments