A binding function is supported to return an object, and I want to return a None when encountering some invalid value, but C++ doesn't has sth. like None, so is there any way I can return a None type? And If so, could you pls give a short example? I've searched the document but can not find a tutorial about returning None type.
Pybind11 defines pybind11::none type, which corresponds to python's None.
You're probably looking for an optional type. If you can use C++17, just use std::optional with #include <pybind11/stl.h>. Otherwise, if you can use Boost, there's boost::optional; the code needed to bind it with pybind11 is in that same link. Otherwise, if you can find some other type that behaves like an optional, you can similarly expose it to pybind11. You may be able to use std::experimental::optional if neither option works for you.
this is working. pybind11::cast
@naugustin hi, would you show me a simple example about how to do that? thanks:)
$ cat example.cpp
#include <pybind11/pybind11.h>
namespace py = pybind11;
py::object ret_none()
{
return py::cast<py::none>(Py_None);
`}
PYBIND11_MODULE(example, mod)
{
mod.def("ret_none", &ret_none);
}
$ c++ -O3 -Wall -shared -std=c++11 -undefined dynamic_lookup -I/Library/Frameworks/Python.framework/Versions/2.7/include/python2.7 -I~/Downloads/pybind-pybind11-e4637eb/include example.cpp -o example.so
$ python
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 12:01:12)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
import example
type(example.ret_none())
exit()
@naugustin thanks锛氾級
Came here for the same thing.
Easier than the cast is simply to use the constructor py::none().
Easier than the cast is simply to use the constructor
py::none().
As was mentioned above. The point is that pybind11::none is not properly documented.
Easier than the cast is simply to use the constructor
py::none().As was mentioned above. The point is that
pybind11::noneis not properly documented.
Where was that mentioned? All previous examples used a cast.
Second comment from bstaletic.
The py::none(), list(), etc. classes were originally just intended for pybind11-internal usage, but they are effectively now part of the public API. Their documentation is lacking as a consequence of this history. Outside contributions are welcomed if you would like this to change.
Second comment from bstaletic.
I'm not sure what's going on here but I see only one comment from bstaletic in this thread (from August 4, 2018)?
Second comment from bstaletic.
I'm not sure what's going on here but I see only one comment from bstaletic in this thread (from August 4, 2018)?
Second comment in the thread, by me. It talks about py::none. Anyway, we can close this as there's no actual issue here.
Most helpful comment
this is working. pybind11::cast