Skip to content

Implicit conversion from Null when inside a vector #1382

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
afryt opened this issue Apr 27, 2018 · 4 comments
Closed

Implicit conversion from Null when inside a vector #1382

afryt opened this issue Apr 27, 2018 · 4 comments

Comments

@afryt
Copy link

afryt commented Apr 27, 2018

Can't make an implicit conversion from None (py::none or py::object) to my class work.
It is the same issue as #642 but I'd like to provide a non-obscure use case.

In the interface I'm writing I'd like to provide a constructor from a Python list. The elements of the list can be double, string and None (ideally). The constructor being exposed is this one:
A::A(const vector<B>& l)
I expose it using

py::class_<A> m(module, "A");
m.def(py::init<vector<B>>&>())

I'd like to call this using:

A([None, 1.0, "string"])

I registered implicit conversion from double and string to B and it flies, that is I can create object A using A([1.0, 'string']). This works because B has implicit conversions:
B.def(py::init<double>()).def(py::init<std::string>()).def(py::init<>());
and a list of py::implicitly_convertible<double, B>()....

Question: How to I add implicit conversion from Python None to use B() when in a list?

@tboyce021
Copy link

I'm running into this same issue with a map. Did you ever figure out a workaround?

@afryt
Copy link
Author

afryt commented Aug 4, 2018

No, unfortunately I haven't. If you come up with something please share.

@bstaletic
Copy link
Collaborator

b_class.def("__init__" [](py::object o) {
    if (o.is_none()) return B{};
    else throw py::type_error("boom");
});

If this doesn't solve it, feel free to reopen the issue.

@YannickJadoul
Copy link
Collaborator

YannickJadoul commented Jul 27, 2020

Or #include <pybind11/stl.h> + std::optional<...>.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants