polortiz40
polortiz40

Reputation: 418

How to pass a default numpy array argument to a function in pybind11?

I am defining a method that takes py::array_t< double > and py::array_t< bool > as arguments. How can I tell pybind11 to default those arguments to an array of my choice? (say np.array([0, 0, 0]))

I have tried adding the default via "Argument"_a = py::array_T({0, 0, 0}) but when I call it itells me 'array has incorrect number of dimensions: 3; expected 1'

m.def("foo", [](py::array_t<double> Arg1,                        
                py::array_t<bool> Arg2){

        auto bar = Arg1.unchecked<1>();
        auto bar2 = Arg2.unchecked<1>();

                    '''other simple code that doesn't alter bar or bar2'''

        return bar;
    },
    "Arg1"_a,
    "Arg2"_a = py_array<bool> ({0, 0, 0})
);

Upvotes: 0

Views: 876

Answers (1)

Sergei
Sergei

Reputation: 1799

The problem is that value of your default argument is 3d array with zero-length dimensions, instead of 1d array of three elements.

The constructor you are calling with py_array<bool> ({0, 0, 0}):

    explicit array_t(ShapeContainer shape, const T *ptr = nullptr, handle base = handle())
        : array_t(private_ctor{}, std::move(shape),
                ExtraFlags & f_style ? f_strides(*shape, itemsize()) : c_strides(*shape, itemsize()),
                ptr, base) { }

https://github.com/pybind/pybind11/blob/c9d32a81f40ad540015814edf13b29980c63e39c/include/pybind11/numpy.h#L861

Upvotes: 1

Related Questions