Open
Description
Issue description
Objects of classes created with pybind11 can't be pretty printed with the pprint module if the result is larger than the given width.
This only happens with python3.
It used to happen with cython too, but cython stopped using 'instancemethod', which solved the issue. The pprint bug was discarded because "Functions/methods should be immutable, so yes, I think it is a safe assumption that they should be hashable":
https://bugs.python.org/issue33395
Reproducible example code
example.cpp:
#include <pybind11/pybind11.h>
#include <string>
namespace py = pybind11;
struct Dummy
{
std::string text;
};
PYBIND11_MODULE(example, m) {
using namespace pybind11::literals;
py::class_<Dummy>(m, "Dummy")
.def(py::init<std::string>(), "text"_a)
.def_readonly("text", &Dummy::text)
.def("__str__", [](const Dummy& w) { return w.text; })
.def("__repr__", [](const Dummy& w) { return w.text; });
}
bug.py:
import example
import pprint
pprint.pprint(example.Dummy('abc'), width=3)
Result:
Traceback (most recent call last):
File "bug.py", line 4, in <module>
pprint.pprint(example.Dummy('abc'), width=2)
File "/usr/lib/python3.8/pprint.py", line 53, in pprint
printer.pprint(object)
File "/usr/lib/python3.8/pprint.py", line 148, in pprint
self._format(object, self._stream, 0, 0, {}, 0)
File "/usr/lib/python3.8/pprint.py", line 173, in _format
p = self._dispatch.get(type(object).__repr__, None)
TypeError: unhashable type: 'instancemethod'