Search code examples
pythonc++pybind11

Does pybind11 default arugments expression been called every time when the python API been invoked?


I'm trying to add an expression as default arguments to my python function API, which is implemented by pybind11.

For example, here's the C++ function:

void my_print(std::chrono::system_clock::time_point tp = std::chrono::system_clock::now()) {
  std::cout << tp << std::endl;
}

PYBIND11_MODULE(my_module, m) {
  m.doc() = "my python module implement in pybind11";
  m.def("my_print", &my_print, py::arg("tp") = std::chrono::system_clock::now());
}

Now I'm wonderring that, the expression = std::chrono::system_clock::now(), I want it been called everytime I invoke this my_print API in python script.

But I'm not sure, is this expression been called everytime this API been invoked in python ? Or this expression is only been called once when this python module been load in python ?


Solution

  • This is evaluated once, during the (runtime) initialization of the pybind bindings.

    The way this feature is implemented is by overloading operator= of py::arg to return a different type, py::arg_v (short for argument with default value).