Action Engine
Loading...
Searching...
No Matches
utils_pybind11.h
1// Copyright 2025 Google LLC
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#ifndef ACTIONENGINE_PYBIND11_ACTIONENGINE_UTILS_H_
16#define ACTIONENGINE_PYBIND11_ACTIONENGINE_UTILS_H_
17
18#include <memory>
19
20#include <absl/status/statusor.h>
21#include <pybind11/attr.h>
22#include <pybind11/cast.h>
23#include <pybind11/pybind11.h>
24#include <pybind11/pytypes.h>
25
26namespace act::pybindings {
27
28namespace py = ::pybind11;
29
39template <typename T>
40auto MakeSameObjectRefConstructor() {
41 return py::init([](const std::shared_ptr<T>& other) { return other; });
42}
43
57template <typename T>
58std::shared_ptr<T> ShareWithNoDeleter(T* ptr) {
59 return std::shared_ptr<T>(ptr, [](T*) {});
60}
61
73py::object& GetGloballySavedEventLoop();
74
86void SaveEventLoopGlobally(const py::object& loop);
87
88void SaveFirstEncounteredEventLoop();
89
107
136absl::StatusOr<py::object> RunThreadsafeIfCoroutine(
137 py::object function_call_result, py::object loop = py::none(),
138 bool return_future = false);
139
140} // namespace act::pybindings
141
142// implementation of PyBind11's machinery for the keep_event_loop_memo
143// annotation.
144template <>
145struct pybind11::detail::process_attribute<
147 : process_attribute_default<act::pybindings::keep_event_loop_memo> {
148 static void precall(function_call&) {
149 act::pybindings::SaveFirstEncounteredEventLoop();
150 }
151};
152
153#endif // ACTIONENGINE_PYBIND11_ACTIONENGINE_UTILS_H_
Annotation for PyBind11 functions to indicate that the event loop should be tracked and saved as a gl...
Definition utils_pybind11.h:106