Search code examples
pythonc++pycxx

What is the proper way to define attributes in a PyCXX extension


I wonder what the proper way is to define attributes in a python extension generated with PyCxx. Currently I have created a subclass of Py::PythonClass as in the official example. I've added behaviors().supportGetattro(); in the initialization function and created a simple override of

Py::Object getattro( const Py::String &name_ )
{
    std::string name( name_.as_std_string( "utf-8" ) );

    if( name == "name" )
    {
        return m_name;
    }
    else
    {
        return genericGetAttro( name_ );
    }
}

So far so good. In python I get the proper value with obj.name, but the only thing that makes me unsatified is that when calling dir(obj) the name attribute does not get listed. How can I change that?


Solution

  • Barry Scott, developer of PyCXX kindly provided a simple solution. The trick is that python asks for the value of __members__ in getattr( const char *_name ) when calling dir(). In this case one can return a Py::List object containing the attribute names as strings.