[C++-sig] boost.python: modifying class getattr
Hans Meine
meine at kogs1.informatik.uni-hamburg.de
Mon Dec 5 17:47:11 CET 2005
On Wednesday 16 November 2005 18:37, David Abrahams wrote:
> > is there a way to modify the type object associated with Foo_ instances
> > so that instead of calling PyObject_GenericGetAttr when an attribute is
> > requested, Python calls a function
> > PyObject *
> > Foo_GetAttr(PyObject *obj, PyObject *name)
> > ?
>
> PyTypeObject* Foo_t = (PyTypeObject*)Foo_.ptr();
> Foo_t->tp_getattro = Foo_GetAttr;
Interesting. In a desperate attempt to make accessing (2-dimensional) point
elements from my Polygon class faster (a native python list of these objects
is twice as fast), I tried to manually set (PyTypeObject*)Foo_.ptr()
->tp_as_sequence->sq_item to my hand-crafted __getitem__ implementation...
which made it *slower*. ;-)
Obviously, my __getitem__ using extract<Vector2Array>(self)() is doing an
extra type-checking which my previously used boost::python function did not
do (since boost knew that self contained my object), and - I should have had
a little more confidence in the power of boost::python - was already
registered in the special tp_as_sequence->sq_item slot (which triggered an
assert I had put in before overwriting sq_item). ;-}
That's cool. What a pity that I spent my afternoon trying to optimize where
it was already done optimally. ;-/
Obviously, the only remaining advantage of a python list is that it contains
readily-wrapped python objects that can simply be returned (after an
incref())?!
--
Ciao, / /
/--/
/ / ANS
More information about the Cplusplus-sig
mailing list