From: Diane Trout Date: Thu, 6 Sep 2007 22:44:54 +0000 (+0000) Subject: make annotations sequenceable from python X-Git-Url: http://woldlab.caltech.edu/gitweb/?p=mussa.git;a=commitdiff_plain;h=b2b25b0aeb07c0a77e5a552ae0c29238578442ea make annotations sequenceable from python e.g. l = [ x for x in mussa.annotations("value") returns [('name', 'value') --- diff --git a/py/annotations.cpp b/py/annotations.cpp index 4c0c53c..453406d 100644 --- a/py/annotations.cpp +++ b/py/annotations.cpp @@ -8,11 +8,30 @@ using namespace boost::python; #include "alg/annotations.hpp" - #include "stl_container_adapter.hpp" +#include + +typedef std::pair pair_string; + +struct pair_string_to_tuple +{ + static PyObject * convert(pair_string const &p) { + PyObject *key = PyString_FromString(p.first.c_str()); + PyObject *value = PyString_FromString(p.second.c_str()); + PyObject *tuple = PyTuple_New(2); + if (key == 0 or value == 0 or tuple == 0) + throw std::runtime_error("Allocation Error"); + + PyTuple_SetItem(tuple, 0, key); + PyTuple_SetItem(tuple, 1, value); + return tuple; + } +}; + void export_annotations() { + to_python_converter(); class_("annotations", init()) .add_property("name", &Annotations::name, &Annotations::setName) @@ -21,10 +40,12 @@ void export_annotations() .def("__getitem__", &map_item::get, return_value_policy()) .def("__setitem__", &map_item::set) + .def("__iter__", iterator()) .def("__len__", &Annotations::size) .def("keys", &map_item::keys) .def("values", &map_item::values) .def("items", &map_item::items) + ; //register_ptr_to_python< AnnotationsRef >(); diff --git a/py/test/TestAnnotations.py b/py/test/TestAnnotations.py index 32949d4..6c432bd 100644 --- a/py/test/TestAnnotations.py +++ b/py/test/TestAnnotations.py @@ -19,8 +19,9 @@ class TestAnnotations(unittest.TestCase): def testIter(self): name_value = 'name_value' a = mussa.annotations(name_value) - # It'd be nice if this worked. - # l = [ x for x in a ] + l = [ x for x in a ] + self.failUnlessEqual(len(l), 1) + self.failUnlessEqual(l[0], ('name', 'name_value')) def suite(): return unittest.makeSuite(TestAnnotations, 'test')