Search code examples
pythonc++pybind11

Function with dynamic return type in pybind11


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?


Solution

  • 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.