#include <torch/csrc/utils/pybind.h>
#include <optional>
#include <tuple>
namespace torch::impl {
template <typename GuardT, typename... Args>
struct RAIIContextManager {
explicit RAIIContextManager(Args&&... args)
: args_(std::forward<Args>(args)...) {}
void enter() {
auto emplace = [&](Args... args) {
guard_.emplace(std::forward<Args>(args)...);
};
std::apply(std::move(emplace), args_);
}
void exit() {
guard_ = std::nullopt;
}
private:
std::optional<GuardT> guard_;
std::tuple<Args...> args_;
};
template <typename GuardT, typename... GuardArgs>
void py_context_manager(const py::module& m, const char* name) {
using ContextManagerT = RAIIContextManager<GuardT, GuardArgs...>;
py::class_<ContextManagerT>(m, name)
.def(py::init<GuardArgs...>())
.def("__enter__", [](ContextManagerT& guard) { guard.enter(); })
.def(
"__exit__",
[](ContextManagerT& guard,
const py::object& ,
const py::object& ,
const py::object& ) { guard.exit(); });
}
template <typename GuardT, typename... Args>
struct DeprecatedRAIIContextManager {
explicit DeprecatedRAIIContextManager(Args&&... args) {
guard_.emplace(std::forward<Args>(args)...);
}
void enter() {}
void exit() {
guard_ = std::nullopt;
}
private:
std::optional<GuardT> guard_;
std::tuple<Args...> args_;
};
template <typename GuardT, typename... GuardArgs>
void py_context_manager_DEPRECATED(const py::module& m, const char* name) {
using ContextManagerT = DeprecatedRAIIContextManager<GuardT, GuardArgs...>;
py::class_<ContextManagerT>(m, name)
.def(py::init<GuardArgs...>())
.def("__enter__", [](ContextManagerT& guard) { guard.enter(); })
.def(
"__exit__",
[](ContextManagerT& guard,
const py::object& ,
const py::object& ,
const py::object& ) { guard.exit(); });
}
}