Search code examples
pythonswig

repr function in swig for python


I have a Swig wrapper to use in python. For one of my class, I have created a repr function as follows

%module myModule
%{
    #include <string>
    #include <sstream>
%}

%extend myClass {
std::string __repr__()
{
    std::ostringstream ss;
    ss << "MyClass(attr1=" << $self->attr1 << ", attr2=" << $self->attr1 << ")";

    return ss.str();
}}

However when I compile the wrapper and use it in python, I get the following error __repr__ returned non-string (type SwigPyObject)

How can I fix this?


Solution

  • Here's a working example of my comment in the question in a self-contained SWIG interface file. As mentioned you need to include SWIG's std_string.i support interface:

    example.i

    %module example
    
    %{
    #include <string>
    #include <sstream>
    %}
    
    %include <std_string.i>
    
    // Filling in missing minimal class definition.
    %inline %{
    class myClass {
    public:
        int attr1;
        int attr2;
        myClass(int a1, int a2) : attr1(a1), attr2(a2) {}
    };
    %}
    
    %extend myClass {
    std::string __repr__()
    {
        std::ostringstream ss;
        ss << "MyClass(attr1=" << $self->attr1 << ", attr2=" << $self->attr1 << ")";
    
        return ss.str();
    }
    }
    

    Demo:

    >>> import example as e
    >>> m = e.myClass(5,7)
    >>> m
    MyClass(attr1=5, attr2=5)