pybind11: how to implement a with context manager

Viewed 1028

I'm trying to implement a Python with context manager with pybind11.

Following Python's documentation, my first version is:

    py::class_<MyResource> (module, "CustomResource", "A custom ressource")
    .def("__enter__", [&] (MyResource& r) { r.lock(); }
        , "Enter the runtime context related to this object")
    .def("__exit__", [&] (MyResource& r, void* exc_type, void* exc_value, void* traceback) { r.unlock(); }
        , "Exit the runtime context related to this object")
    ;

I don't know what the types of exc_type, exc_value and traceback. I guess they can be simple pybind11::object?

Are they more specific bindings, I can use?

1 Answers

Indeed these arguments will come as Python objects, so you should use pybind11::object type for them. Using void* is not a solution.

Pybind11 is probably the best Python wrapper for C++ mechanism that uses C++ as its language at the moment.

Related