Skip to content

pybind11/stl.h converts string to vector<string> #1258

Closed
@zpz

Description

@zpz
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <iostream>
#include <string>
#include <vector>

namespace py = pybind11;


class My {
    private:
        std::string _name;
        std::vector<std::string> _names;

    public:
        My(std::string name) : _name(name) {}
        My(std::vector<std::string> names) : _names(names) {}

        void print() const {
            if (_name.length() > 0) {
                std::cout << _name << std::endl;
            }
            if (_names.size() > 0) {
                for (auto const & v : _names) {
                    std::cout << "-" << v << "-";
                }
                std::cout << std::endl;
            }
        }
};


PYBIND11_MODULE(example, m) {
    py::class_<My>(m, "My")
        .def(py::init<std::string>())
        .def(py::init<std::vector<std::string>>())
        .def("print", &My::print);
}

In Python,

>>> from example import My
>>> My('myname').print()
myname
>>> 

Now change the binding code to list the vector<string> constructor before the string constructor. Then in Python,

>>> from example import My
>>> My('myname').print()
-m--y--n--a--m--e-

If I do not include stl.h, then this does not happen---the vector<string> constructor wouldn't take a string parameter. Clearly the behavior listed above is automatic conversion by stl.h.

However, in my opinion a str should never be auto converted to a vector<string>. Because on the Python side it's trivial to convert a str to a list, the user should explicitly do this conversion if they wants to use a vector binding.

Because stl.h is often useful, the chance of the above situation happening is not low.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions