[C++-sig] __str__ method for wrapper classes
Alex Mohr
amohr at pixar.com
Tue Nov 14 18:38:13 CET 2006
> I want to be able to print MyClass as a string in python. I
> added .def(str(self)) to the class object for the wrapper (MyClassWrap)
> thinking it would work but, python complains that the __str__ method did not
> match the C++ signature:
>
> Boost.Python.ArgumentError: Python argument types in
> MyClass.__str__(MyClass)
> did not match C++ signature:
> __str__(MyClassWrap {lvalue})
>
> I think the problem is that I defined the __str__ method for MyClassWrap and
> not for MyClass. Since MyClassWrap also inherits from wrapper, it can't use
> MyClass's extraction operator. I don't have a class_ object for MyClass. I
> only have it for MyClassWrap and the other classes that inherit from MyClass.
> How do I fix this?
From a cursory inspection, I believe this is the same bug as that
mentioned in this thread:
http://mail.python.org/pipermail/c++-sig/2006-September/011336.html
which David has already fixed in CVS. Unfortunately, I don't know when
the next version of boost (and boost python) will be out, so I can't say
when you'll get it.
As a workaround, I think you can do something like this in your wrapping
code:
class<...>(...)
.def("__str__", boost::lexical_cast<std::string, MyClass const &>)
if MyClass is streamable. If it's not, you can always do something
totally custom:
static std::string MyClass__str__(MyClass const &self) {
return std::string("Whatever I want.");
}
class<...>(...)
.def("__str__", MyClass__str__)
Alex
More information about the Cplusplus-sig
mailing list