[C++-sig] [] subscript notation with boost::python

Maik Beckmann beckmann.maik at googlemail.com
Mon Feb 23 19:08:32 CET 2009


Murray Cumming schrieb am Montag 23 Februar 2009 um 12:39:
> I'm trying to support this notation in python:
> something = record["somefieldname"]
[snip]
> I'm now trying to do this with boost::python, like so, because googling
> has suggested that this should work:
>
> boost::python::class_<Glom::PyGlomRecord>("Record")
>   .def("__getitem__", &Glom::PyGlomRecord::getitem)
>   .def("__len__", &Glom::PyGlomRecord::len)
>
> But when I try to use that in Python, I get this error:
> "Boost.Python.class' object is unsubscriptable"
>
> Is there something else that I need to do?

I assume Glom::PyGlomRecord::getitem hasn't the right signature, which isn't 
checked at compile time
{{{
struct PyGlomRecord
{
  whatever_type getitem(boost::python::object subscriptionObj);
};
}}}

Here is an working example
{{{
#include <boost/python.hpp>

namespace bp = boost::python;

struct Subscriptable
{
  double val;
  
  double getitem(bp::object subscriptionObj)
  {
    return this->val;
  }
  
  double setitem(bp::object subscriptionObj, double val)
  {
    this->val = val;
  }  
};

BOOST_PYTHON_MODULE(mypy)
{
  bp::class_<Subscriptable>("Subscriptable")
    .def("__getitem__", &Subscriptable::getitem)
    .def("__setitem__", &Subscriptable::setitem);
}
}}}

HTH,
 -- Maik


More information about the Cplusplus-sig mailing list