Skip to content

Vectorizing POD types #2258

@chaitan94

Description

@chaitan94

Issue description

In the documentation for vectorization, this is mentioned:

Only arithmetic, complex, and POD types passed by value or by const & reference are vectorized; all other arguments are passed through as-is.

However, it seems that if we use a POD type, py::vectorize does not work as expected. When I check the tests, it seems we do test that non-POD types pass through without vectorization, but there are no tests/examples for how to vectorize POD types.

Reproducible example code

#include <pybind11/pybind11.h>
#include <pybind11/numpy.h>

struct PODClass {
    uint32_t value;
};

PYBIND11_MODULE(example, m) {
    pybind11::class_<PODClass>(m, "PODClass")
        .def(pybind11::init<>())
        .def_readwrite("value", &PODClass::value);

    PYBIND11_NUMPY_DTYPE(PODClass, value);

    m.def("pod_passthrough", pybind11::vectorize(
        [](PODClass a) {
            return a;
        }
    ));

    static_assert(std::is_pod<PODClass>::value);  // To ensure we actually do have a POD type
}

This compiles. When we try to use in python, however:

import example
import numpy as np

object_1 = example.PODClass()
object_1.value = 10
object_2 = example.PODClass()
object_2.value = 20
vec = np.array([object_1, object_2])
example.pod_passthrough(vec)
>       example.pod_passthrough(a)
E       TypeError: pod_passthrough(): incompatible function arguments. The following argument types are supported:
E           1. (arg0: numpy.ndarray[pybind11_tests.numpy_vectorize.PODClass]) -> object
E       
E       Invoked with: array([<pybind11_tests.numpy_vectorize.PODClass object at 0x7f662db9de30>,
E              <pybind11_tests.numpy_vectorize.PODClass object at 0x7f6638a3d970>],
E             dtype=object)

Not sure if this is expected or I am doing something wrong.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions