pybind/pybind11

[BUG] Unbound methods should just be functions instead of instancemethod

Open

#2722 aperta il 10 dic 2020

Vedi su GitHub
 (11 commenti) (7 reazioni) (0 assegnatari)C++ (2005 fork)batch import
bughelp wanted

Metriche repository

Star
 (14.677 star)
Metriche merge PR
 (Merge medio 5g 2h) (10 PR mergiate in 30 g)

Descrizione

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'

Guida contributor