How to bind C++ resources into a Python context manager #388
-
Say I have a resource like a simple timer on a class, which makes sense to be acquired and released inside a context manager on the Python side:
How could I expose this on the Python side as a context manager, say like |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
No abstraction for this exists, and there aren't plans to add one. This is how I would do it (likely there are some syntax errors, you will need to adapt it). struct PauseContext { State &state; };
auto state = nb::class_<State>(m, "State")
.def(...);
nb::class_<PauseContext>(state, "PauseContext")
.def("__enter__", [](PauseContext &ctx) { ctx.state.PauseTiming(); })
.def("__exit__", [](PauseContext &ctx, nb::handle, nb::handle, nb::handle) { ctx.state.ResumeTiming(); },
nb::arg().none(), nb::arg().none(), nb::arg().none());
state.def("pause", [](State &s) { return PauseContext{s}; }, nb::rv_policy::reference_internal); |
Beta Was this translation helpful? Give feedback.
No abstraction for this exists, and there aren't plans to add one. This is how I would do it (likely there are some syntax errors, you will need to adapt it).