Default value for pybind11::function #3634
-
Hi, I can do |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
One solution I have found is to combine First you need to define your class: #include <pybind11/pybind11.h>
#include <pybind11/stl.h>
namespace py = pybind11;
class Foo
{
public:
Foo(py::function _function) : func(_function)
{
}
Foo(py::none _none) : func(_none)
{
}
std::variant<py::function, py::none> func;
}; And provide bindings that will utilise these features: py::class_<Foo, std::shared_ptr<Foo>> cls(module, "Foo");
cls.def(py::init([](std::optional<py::function> &func)
{
if (func.has_value())
{
return Foo(func.value());
}
return Foo(py::none());
}),
py::arg("func").none(true) = py::none());
cls.def(
"call_me", [](Foo &self)
{
if (std::holds_alternative<py::none>(self.func))
{
py::print("Function is None!");
return;
}
std::get<py::function>(self.func)();
return;
});
cls.def_property(
"func", [](Foo &self)
{
return self.func;
},
[](Foo &self, std::variant<py::function, py::none> &other)
{
self.func = other;
}); If you try out this module it achieves your use-case goals (hopefully:)):
In fact there could be a better solution but this one came to my mind first, I would be very happy to see more compact way of achieving it. As this one works for Hope you find this answer satisfying! |
Beta Was this translation helpful? Give feedback.
-
To set it to back an invalid state(nullptr), one can use func.release() to reset. Also when py::function is default constructed, it's also in an invalid(nullptr) rather than None state. |
Beta Was this translation helpful? Give feedback.
One solution I have found is to combine
std::optional
andstd::variant
capabilities from C++17.First you need to define your class:
And provide bindings that will utilise these features: