Skip to content
Snippets Groups Projects
Commit 674b4edc authored by Marco Biasini's avatar Marco Biasini
Browse files

make generic property interface more pythonic

Instead of doing a.GetFloatProp('foo'), feel free to use
a.foo. a.foo = 3.0 will create a new float property 'foo'.

This commit is brought to you by ZSO Pilatus
parent 3aa01253
Branches
Tags
No related merge requests found
......@@ -19,7 +19,8 @@
#ifndef GENERIC_PROPERTY_DEF_HH
#define GENERIC_PROPERTY_DEF_HH
#include <boost/python.hpp>
#include <cassert>
#include <ost/log.hh>
/*
Author: Marco Biasini
......@@ -130,6 +131,36 @@ String depr_prop_as_string(C& c, const String& k)
return c.GetPropAsString(k);
}
template <typename C>
boost::python::object get_attr(C& c, const String& k) {
std::map<String,ost::GenericPropValue>::const_iterator
i = c.GetPropMap().find(k);
boost::python::object obj;
if (i != c.GetPropMap().end()) {
switch (i->second.which()) {
case 0:
return boost::python::object(boost::get<String>(i->second));
case 1:
return boost::python::object(boost::get<Real>(i->second));
case 2:
return boost::python::object(boost::get<int>(i->second));
case 3:
return boost::python::object(boost::get<bool>(i->second));
default:
assert(0 && "unhandled type");
}
}
std::string msg = "no such attribute '" + k + "'";
PyErr_SetString(PyExc_AttributeError, msg.c_str());
boost::python::throw_error_already_set();
// throw_error_already_set is not marked noreturn in some versions of
// boost. That's why we need a return statement at the end, even if we
// never get here!
return obj;
}
template <typename C, typename O>
void const_generic_prop_def(O& bp_class)
{
......@@ -167,6 +198,7 @@ void const_generic_prop_def(O& bp_class)
.def("GetGenericStringProperty", &depr_get_string_b<C>)
.def("HasGenericProperty", &depr_has_prop<C>)
.def("GetGenericPropertyStringRepresentation", &depr_prop_as_string<C>)
.def("__getattr__", &get_attr<C>)
;
}
......@@ -188,6 +220,10 @@ void generic_prop_def(O& bp_class)
.def("SetGenericBoolProperty", &depr_set_bool<C>)
.def("SetGenericStringProperty", &depr_set_string<C>)
.def("RemoveProp", &C::RemoveProp)
.def("__setattr__", &C::SetBoolProp)
.def("__setattr__", &C::SetIntProp)
.def("__setattr__", &C::SetStringProp)
.def("__setattr__", &C::SetFloatProp)
;
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment