Function with dynamic return type in pybind11

Question:

In python you can define functions which dynamically return different types:

def func(b):
   if b:
      return 42
   else:
      return "hello"

How can I implement in C++ a function like this and export it with pybind11?

Ideally it would be something like:

m.def("func", [](bool b) -> py::object {
   if(b)
      return /* something */(42);
   else
      return /* something */("hello");
});

However, I did not find how to construct py::object using objects of registered C++ types.

Is this possible at all?

Asked By: gigabytes

||

Answers:

The solution, thanks to @Osyotr’s comment, is very simple:

#include <variant>
#include <string>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>

...

m.def("func", [](bool b) -> std::variant<int, std::string> {
   if(b)
      return {42};
   else
      return {"hello"};
});

PyBind11 takes automatically care of providing the right component of the variant to the Python side.

Answered By: gigabytes
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.