pybind / pybind/pybind11

[FEAT] format_descriptor of pair<float,float>

Open
#2,991 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
C++
Stars
18k
Forks
2.3k
Avg merge
5d 17h
Merged PRs (30d)
10

Description

The following code, using std::array, is working fine

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

namespace py=pybind11;
typedef std::array<double,2> P;
typedef std::vector<P> V;
PYBIND11_MAKE_OPAQUE(V);
PYBIND11_MODULE(u, m) {
  py::bind_vector<V>(m, "VectorPair", py::buffer_protocol());
  m.def("fff",[](){
      V a(4000, {1,2});
      return py::array(py::cast(std::move(a)));
      });
}

However, if I replace the array with

typedef std::pair<double,double> P;

it fails to compile

static_assert(vector_has_data_and_format::value, "There is not an appropriate format descriptor for this vector");

and I need to add for instance

namespace pybind11 { template<>struct format_descriptor<P>:format_descriptor<double[2]>{}; }

to let it work again.

I was wondering if it would make sense for pybind11 to provide such specializations for std::pair and std::tuple when all the types are the same, like it already does for std::array. One drawback I can think of is that when the types differ, say std::pair<int,float>, we probably want something like PYBIND11_NUMPY_DTYPE(P, first, second); instead (with some standard libraries we may also need to fake namespace std { template<>struct is_trivially_copyable<P>:true_type{}; }), and that would make the case of equal types an exception. I guess I would also be ok with getting a structured array, I can always use view to turn it into the array I want...

#1495 is the closest issue I found in the list, but different.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by tracing the format_descriptor specializations and the vector_has_data_and_format assertion involved in py::array conversion, then compare the existing std::array handling with std::pair and std::tuple. Done means the supported same-type pair and tuple cases compile and behave as intended, while differing element types remain compatible with the documented structured-dtype approach.

Written by the indexing model from the issue text.

Assessment

Tech stack
cpp, numpy, python
Domain
api
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
42/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.