Open allanleal opened 4 years ago
Assume I have class/struct Foo and operator std::ostream& operator<<(std::ostream&, const Foo&). In Boost.Python, one can use something like:
Foo
std::ostream& operator<<(std::ostream&, const Foo&)
.def(str(self))
to enable the use of print(foo) from Python. See discussion here.
print(foo)
Currently, I'm only aware of the following usage to get print(foo) to work using pybind11:
.def("__str__", [](const Foo& self) { std::stringstream ss; ss << self; return ss.str(); })
I wonder if there is a more convenient way of doing this already in pybind11.
This is what I do:
https://github.com/scikit-hep/boost-histogram/blob/40839b759492a7424dd83951f42ac8ce71cb4b9b/include/bh_python/pybind11.hpp#L39-L45
But it would be nice to have this common need more accessible. Though py::str already has meaning. Also, how would you target __repr__ vs. __str__?
py::str
__repr__
__str__
Assume I have class/struct
Foo
and operatorstd::ostream& operator<<(std::ostream&, const Foo&)
. In Boost.Python, one can use something like:to enable the use of
print(foo)
from Python. See discussion here.Currently, I'm only aware of the following usage to get
print(foo)
to work using pybind11:I wonder if there is a more convenient way of doing this already in pybind11.