Skip to content

Convert to object #2

Closed
Closed
@mrzv

Description

@mrzv

I want to assign a class, exposed to Python through pybind11, to a module's attribute. This requires converting it to an object. To make things concrete, I want to use RAII pattern to initialize and finalize MPI whenever the module is imported. The code looks roughly like this:

struct environment
{
  environment()    { MPI_Init(0,0); }
  ~environment()   { MPI_Finalize(); }
};

py::class_<environment>(m, "environment")
  .def("__repr__", [](const environment&) { return "MPI Environment"; });

m.attr("env") = py::detail::type_caster<environment>::cast(new environment, py::return_value_policy::automatic, m.ptr());

This works, but it's the last line that bothers me. Is this really the right way to do this? Have I missed some cleaner way? Besides being verbose, having to access detail namespace seems wrong. I'm probably missing something, but if not, maybe it's worth adding clean support for this use-case?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions