Skip to content

Default value for pybind11::function #3634

Answered by jiwaszki
porrashuang asked this question in Q&A
Discussion options

You must be logged in to vote

One solution I have found is to combine std::optional and std::variant capabilities from C++17.

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 

Replies: 2 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by porrashuang
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants