Boost logo

Boost :

From: Donavon Keithley (keithley_at_[hidden])
Date: 2001-05-04 17:02:00

I'm experimenting with a binary tree structure using polymorphic nodes, but
I seem to be losing object identity on the Python side.

        struct BaseNode
          BaseNode* l;
          BaseNode* r;

        struct DerivedNode : public BaseNode
          int foo;

Following the cookbook, I wrap BaseNode* as follows:

        PyObject* to_python(BaseNode* p)
        PyObject* to_python(const BaseNode* p)
          return to_python(const_cast<BaseNode*>(p));

Similarly for DerivedNode. And then build the classes like so:

        boost::python::class_builder<BaseNode> BaseNode_class(this_module,
        BaseNode_class.def_read_write(&BaseNode::l, "l");
        BaseNode_class.def_read_write(&BaseNode::r, "r");

        boost::python::class_builder<DerivedNode> DerivedNode_class(this_module,
        DerivedNode_class.def_read_write(&DerivedNode::foo, "foo");
        DerivedNode_class.declare_base(BaseNode_class, python::without_downcast);

In Python:

>>> dn0 = DerivedNode()
>>> = 0
>>> dn1 = DerivedNode()
>>> = 1
>>> dn0.l = dn1
>>> dn0.l
<BaseNode object at 00D46540> <-- Uh oh...
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: foo

This clearly doesn't work, so my question is what would be a correct

I've noticed -- and this is probably related -- that if I instantiate
BaseNodes, it sort of works:

>>> bn0 = BaseNode()
>>> bn1 = BaseNode()
>>> bn0.l = bn1

I've verified that bn0.l and bn1 refer to the same instance of BaseNode on
the C++ side, in spite of the fact that their Python identities are not the

>>> id(bn0.l)
>>> id(bn1)

I only barely understand how BPL works under the hood, but it seems that
what I need here is proxies on the Python side -- that is, a to_python
conversion that always returns the same PyObject for the same BaseNode* or

Any insight would be greatly appreciated!

Boost list run by bdawes at, gregod at, cpdaniel at, john at