Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Named Default Arguments in pybind11

I'm using pybind11 to wrap a C++ class method in a conversion lambda "shim" (I must do this because reasons). One of the method's arguments is defaulted in C++.

class A
{
   void meow(Eigen::Matrix4f optMat = Eigen::Matrix4f::Identity());
};

In my pybind code I want to preserve this optional parameter:

py::class_<A>(m, "A")
       .def(py::init<>())
       .def("meow",
            [](A& self, Eigen::Matrix4f optMat = Eigen::Matrix4f::Identity()) 
            {
               return self.meow( optMat ); 
            });

How do I make optMat an optional named argument in the generated Python code?

like image 235
Adi Shavit Avatar asked Jul 29 '19 05:07

Adi Shavit


People also ask

What is default arguments give example?

Default arguments are overwritten when the calling function provides values for them. For example, calling the function sum(10, 15, 25, 30) overwrites the values of z and w to 25 and 30 respectively.

Which is the default argument?

In computer programming, a default argument is an argument to a function that a programmer is not required to specify. In most programming languages, functions may take one or more arguments. Usually, each argument must be specified in full (this is the case in the C programming language).

What are default arguments and what are keyword arguments?

They are – Default, Keyword, and Arbitrary Arguments. Keyword arguments allow us to employ any order, whereas default arguments assist us to deal with the absence of values.


1 Answers

Just add them after the lambda:

py::class_<A>(m, "A")
    .def(py::init<>())
    .def("meow",
         [](A& self, Eigen::Matrix4f optMat) {
             return self.meow(optMat); 
         },
         py::arg("optMat") = Eigen::Matrix4f::Identity());
like image 122
Mika Fischer Avatar answered Oct 14 '22 04:10

Mika Fischer