How to bind a C++ class to a Python context manager #1384
|
This is close to #388, but different because I want my class to be able to be directly used in a context manager. I don't need to do anything in with Class() as object:
object.do_something()Is this possible in nanobind? I tried to adapt the example from #388, but it doesn't work for me. I'm assuming I need to do something in the nb::class_<Class>(m, "Class")
.def("__enter__", [](Class &ctx) { })
.def("__exit__", [](Class &ctx, nb::handle, nb::handle, nb::handle) { ctx.close(); },
nb::arg().none(), nb::arg().none(), nb::arg().none()); |
Replies: 1 comment
|
Hey! I'm doing this in a project of mine wrapping Google Benchmark. The fix for you should be as simple as The |
Hey! I'm doing this in a project of mine wrapping Google Benchmark. The fix for you should be as simple as
return ctx;in the body of__enter__as you suspected, check this for reference: https://github.com/nicholasjng/mew/blob/d5d2790a8f18b019195bc263da0e807d481e52f6/src/_mew/state.cpp#L49-L63The
nb::sig()annotation there is useful because it follows Python's context manager protocol exactly and outputs a neatly annotated stub that doesn't trip type checkers, but it might be overkill for your purposes.