Skip to content

How to bind C++ resources into a Python context manager #388

Answered by wjakob
nicholasjng asked this question in Q&A
Discussion options

You must be logged in to vote

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);

Replies: 1 comment 3 replies

Comment options

You must be logged in to vote
3 replies
@nicholasjng
Comment options

@nicholasjng
Comment options

@wjakob
Comment options

Answer selected by nicholasjng
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants