[lxml-dev] the subelements of my tree are moving alone

Stefan Behnel stefan_ml at behnel.de
Sat Mar 14 09:47:13 CDT 2009

[and to the list]

TP wrote:
> I have derived custom classes from ET._ElementTree and ET.ElementBase to
> obtain a custom tree suited to my needs.

It obviously depends on what you do with it, but I'm not so sure that
subclassing the _ElementTree class is a good idea. It's not wrong in
general, but maybe writing your own tree wrapper would be better.

> It works perfectly, but it seems that the nodes under the root node (the
> subelements) move sometimes "alone". The tree structure is kept, but the
> address of the elements in memory is changing. As the structure is kept, it
> is not a problem for lxml use only: I can walk in the tree, doing what I
> need.
> But the problem is that I use this custom tree as the underlying data
> structure for a PyQt custom QTreeWidget. In this widget, I use the
> method "internalPointer()" of QModelIndex instances (as proposed in the
> chapter 16 of book "Rapid GUI Programming with Python
> and Qt" by Mark Summerfield (around p.500)).
> The problem is that if the nodes move, the "internalPointer()" of Qt are not
> up to date: I obtain segmentation faults.
> Is this normal that nodes of the tree move in memory *alone*? Is this due to
> the garbage collector? If yes, how to keep my pointers up to date?

Here's some documentation:


It's not only the "pointer", it's the Element instances that are replaced.
It may be that "internalPointer()" (never heard of it, but I assume it's
some kind of backpointing mechanism) does not respect Python's reference
counting, so that the Element object gets garbage collected.

A simple way to work around this is to keep a reference to all Element
objects in the tree, initialised as

	my_tree.element_cache = list(root_element.iter())

But keep in mind that this needs to be maintained on tree changes.


More information about the lxml mailing list