2727#include " absl/strings/str_format.h"
2828#include " absl/types/span.h"
2929#include " common/value.h"
30+ #include " runtime/embedder_context.h"
3031#include " runtime/function.h"
3132#include " py_cel_env.h"
3233#include " py_cel_type.h"
@@ -41,6 +42,17 @@ namespace cel_python {
4142
4243namespace py = ::pybind11;
4344
45+ namespace {
46+
47+ static std::shared_ptr<PyCelEnv> GetEnvFromContext (
48+ const cel::Function::InvokeContext& context) {
49+ ABSL_CHECK (context.embedder_context ()); // Crash OK: all call sites are local
50+ // to the library.
51+ return *context.embedder_context ()->Get <std::shared_ptr<PyCelEnv>*>();
52+ }
53+
54+ } // namespace
55+
4456void PyCelFunction::DefinePythonBindings (pybind11::module & m) {
4557 py::class_<PyCelFunction, std::shared_ptr<PyCelFunction>>(m, " Function" )
4658 .def (py::init<std::string, std::vector<PyCelType>, bool , PyObject*>(),
@@ -65,12 +77,9 @@ PyCelFunction::~PyCelFunction() {
6577 PyGILState_Release (gil_state);
6678};
6779
68- PyCelFunctionAdapter::PyCelFunctionAdapter (const std::shared_ptr<PyCelEnv>& env,
69- std::string function_name,
80+ PyCelFunctionAdapter::PyCelFunctionAdapter (std::string function_name,
7081 PyObject* py_function)
71- : env_(env),
72- function_name_ (std::move(function_name)),
73- py_function_(py_function) {
82+ : function_name_(std::move(function_name)), py_function_(py_function) {
7483 Py_XINCREF (py_function_);
7584}
7685
@@ -85,12 +94,13 @@ absl::StatusOr<cel::Value> PyCelFunctionAdapter::Invoke(
8594 const cel::Function::InvokeContext& context) const {
8695 ABSL_CHECK (PyGILState_Check ());
8796
97+ std::shared_ptr<PyCelEnv> env = GetEnvFromContext (context);
8898 PY_CEL_ASSIGN_OR_RETURN (auto py_arena,
8999 PyCelArena::FromProtoArena (context.arena ()));
90100 PyObject* py_args = PyTuple_New (args.size ());
91101 for (int i = 0 ; i < args.size (); ++i) {
92102 PyTuple_SetItem (py_args, i,
93- CelValueToPyObject (args[i], env_ , py_arena,
103+ CelValueToPyObject (args[i], env , py_arena,
94104 /* plain_value=*/ true ));
95105 }
96106 PyObject* result = PyObject_CallObject (py_function_, py_args);
@@ -105,7 +115,7 @@ absl::StatusOr<cel::Value> PyCelFunctionAdapter::Invoke(
105115 return absl::StrFormat (" Python function '%s'" ,
106116 PyUnicode_AsUTF8 (PyObject_Repr (py_function_)));
107117 },
108- env_ , context.arena ());
118+ env , context.arena ());
109119};
110120
111121} // namespace cel_python
0 commit comments