pybind / pybind11

Seamless operability between C++11 and Python
https://pybind11.readthedocs.io/
Other
15.72k stars 2.11k forks source link

[FEAT] str operator like Boost.Python #2518

Open allanleal opened 4 years ago

allanleal commented 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:

.def(str(self))

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:

.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.

henryiii commented 4 years ago

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__?